From bf7b4df7de6a73e12a41d93b1d769c7799043ff1 Mon Sep 17 00:00:00 2001
From: Cristian Morales Vega
Date: Fri, 22 Nov 2024 11:55:49 +0000
Subject: [PATCH 1/2] Update gcc rules to 14.2
The Fortran-only aliasing, align-commons, ampersand, array-temporaries,
character-truncation, conversion-extra, function-elimination,
implicit-interface, implicit-procedure, intrinsic-shadow,
intrinsics-std, line-truncation, real-q-constant, surprising, underflow
and unused-dummy-argument warnings have been removed.
-Wsystem-headers has also been removed since it's not a warning, it's an
option that affects whether warnings in system headers are reported.
-Wno-aggressive-loop-optimizations and -Wno-builtin-declaration-mismatch
have been replaced with the correct -Waggressive-loop-optimizations and
-Wbuiltin-declaration-mismatch.
---
.../compiler/gcc/CxxCompilerGccSensor.java | 22 +-
.../src/main/resources/compiler-gcc.xml | 9226 ++++++++++++-----
.../gcc/CxxCompilerGccRuleRepositoryTest.java | 2 +-
cxx-sensors/src/tools/gcc_createrules.py | 321 +
4 files changed, 7107 insertions(+), 2464 deletions(-)
create mode 100755 cxx-sensors/src/tools/gcc_createrules.py
diff --git a/cxx-sensors/src/main/java/org/sonar/cxx/sensors/compiler/gcc/CxxCompilerGccSensor.java b/cxx-sensors/src/main/java/org/sonar/cxx/sensors/compiler/gcc/CxxCompilerGccSensor.java
index 5b4340e9b..e47a6a9f3 100644
--- a/cxx-sensors/src/main/java/org/sonar/cxx/sensors/compiler/gcc/CxxCompilerGccSensor.java
+++ b/cxx-sensors/src/main/java/org/sonar/cxx/sensors/compiler/gcc/CxxCompilerGccSensor.java
@@ -115,7 +115,27 @@ protected String alignId(@Nullable String id) {
if (id == null || "".equals(id)) {
id = DEFAULT_ID;
}
- return id.replaceAll("=$", "");
+ id = id.replaceAll("=$", "");
+
+ switch(id) {
+ case "-Wc++0x-compat":
+ id = "-Wc++11-compat";
+ break;
+ case "-Wc++1z-compat":
+ id = "-Wc++17-compat";
+ break;
+ case "-Wc11-c2x-compat":
+ id = "-Wc11-c23-compat";
+ break;
+ case "-Wmissing-format-attribute":
+ id = "-Wsuggest-attribute=format";
+ break;
+ case "-Wmissing-noreturn":
+ id = "-Wsuggest-attribute=noreturn";
+ break;
+ }
+
+ return id;
}
@Override
diff --git a/cxx-sensors/src/main/resources/compiler-gcc.xml b/cxx-sensors/src/main/resources/compiler-gcc.xml
index 83e153092..8d3ca7773 100644
--- a/cxx-sensors/src/main/resources/compiler-gcc.xml
+++ b/cxx-sensors/src/main/resources/compiler-gcc.xml
@@ -15,10 +15,9 @@ Follow these steps to make your custom rules available in SonarQube:
Enable the newly created rule in your quality profile
Relaunch an analysis on your projects, et voilà, your custom rules are executed!
-
- ]]>
-
-
+]]>
+
+
unknown
Unknown GCC rule
@@ -27,3200 +26,7503 @@ Follow these steps to make your custom rules available in SonarQube:
By activating this rule, unknown rules in the reports are not discarded but mapped to this rule. This helps to identify unknown rules, e.g. from newer versions of a tool.
- ]]>
-
+]]>
+
INFO
-
+
default
Default compiler warnings
+ Default compiler warnings.
+
+
+ -WNSObject-attribute
+ Warn if the NSObject attribute is applied to a non-typedef
- Default compiler warnings.
-
- CRITICAL
-
+
+
+
-Wabi
Warn about things that will change when compiling with an ABI-compliant compiler
- Warn when G++ generates code that is probably not compatible with the vendor-neutral
- C++ ABI. Although an effort has been made to warn about all such cases, there are probably some
- cases that are not warned about, even though G++ is generating incompatible code. There may also
- be cases where warnings are emitted even though the code that is generated will be compatible.
+ Warn about code affected by ABI changes. This includes code that may
+not be compatible with the vendor-neutral C++ ABI as well as the psABI
+for the particular target.
+
+Since G++ now defaults to updating the ABI with each major release,
+normally -Wabi warns only about C++ ABI compatibility
+problems if there is a check added later in a release series for an
+ABI issue discovered since the initial release. -Wabi warns
+about more things if an older ABI version is selected (with
+-fabi-version=n).
+
+-Wabi can also be used with an explicit version number to
+warn about C++ ABI compatibility with a particular -fabi-version
+level, e.g. -Wabi=2 to warn about changes relative to
+-fabi-version=2.
+
+If an explicit version number is provided and
+-fabi-compat-version is not specified, the version number
+from this option is used for compatibility aliases. If no explicit
+version number is provided with this option, but
+-fabi-compat-version is specified, that version number is
+used for C++ ABI warnings.
+
+Although an effort has been made to warn about
+all such cases, there are probably some cases that are not warned about,
+even though G++ is generating incompatible code. There may also be
+cases where warnings are emitted even though the code that is generated
+is compatible.
+
+You should rewrite your code to avoid these warnings if you are
+concerned about the fact that code generated by G++ may not be binary
+compatible with code generated by other compilers.
+
+Known incompatibilities in -fabi-version=2 (which was the
+default from GCC 3.4 to 4.9) include:
+
+
+- A template with a non-type template parameter of reference type was
+mangled incorrectly:
+
+
extern int N;
+template <int &> struct S {};
+void n (S<N>) {2}
+
+This was fixed in -fabi-version=3.
+
+ - SIMD vector types declared using
__attribute ((vector_size))
were
+mangled in a non-standard way that does not allow for overloading of
+functions taking vectors of different sizes.
- You should rewrite your code to avoid these warnings if you are concerned about the fact that code
- generated by G++ may not be binary compatible with code generated by other compilers.
-
- CRITICAL
-
+The mangling was changed in -fabi-version=4.
+
+ __attribute ((const))
and noreturn
were mangled as type
+qualifiers, and decltype
of a plain declaration was folded away.
+
+These mangling issues were fixed in -fabi-version=5.
+
+- Scoped enumerators passed as arguments to a variadic function are
+promoted like unscoped enumerators, causing
va_arg
to complain.
+On most targets this does not actually affect the parameter passing
+ABI, as there is no way to pass an argument smaller than int
.
+
+Also, the ABI changed the mangling of template argument packs,
+const_cast
, static_cast
, prefix increment/decrement, and
+a class scope function used as a template argument.
+
+These issues were corrected in -fabi-version=6.
+
+ - Lambdas in default argument scope were mangled incorrectly, and the
+ABI changed the mangling of
nullptr_t
.
+
+These issues were corrected in -fabi-version=7.
+
+ - When mangling a function type with function-cv-qualifiers, the
+un-qualified function type was incorrectly treated as a substitution
+candidate.
+
+
This was fixed in -fabi-version=8, the default for GCC 5.1.
+
+ decltype(nullptr)
incorrectly had an alignment of 1, leading to
+unaligned accesses. Note that this did not affect the ABI of a
+function with a nullptr_t
parameter, as parameters have a
+minimum alignment.
+
+This was fixed in -fabi-version=9, the default for GCC 5.2.
+
+- Target-specific attributes that affect the identity of a type, such as
+ia32 calling conventions on a function type (stdcall, regparm, etc.),
+did not affect the mangled name, leading to name collisions when
+function pointers were used as template arguments.
+
+
This was fixed in -fabi-version=10, the default for GCC 6.1.
+
+
+This option also enables warnings about psABI-related changes.
+The known psABI changes at this point include:
+
+]]>
+
+
+
+ -Wabi-tag
+ Warn if a subobject has an abi_tag attribute that the complete object type does not have
+
+ Warn when a type with an ABI tag is used in a context that does not
+have that ABI tag. See C++-Specific Variable, Function, and Type Attributes for more information
+about ABI tags.
+]]>
+
+
+
+ -Wabsolute-value
+ Warn on suspicious calls of standard functions computing absolute values
+
+ Warn for calls to standard functions that compute the absolute value
+of an argument when a more appropriate standard function is available.
+For example, calling abs(3.14)
triggers the warning because the
+appropriate function to call to compute the absolute value of a double
+argument is fabs
. The option also triggers warnings when the
+argument in a call to such a function has an unsigned type. This
+warning can be suppressed with an explicit type cast and it is also
+enabled by -Wextra.
+]]>
+
+
-Waddress
Warn about suspicious uses of memory addresses
- Warn about suspicious uses of memory addresses. These include using the address of
- a function in a conditional expression, such as "void func(void); if (func)", and comparisons
- against the memory address of a string literal, such as "if (x == "abc")". Such uses typically
- indicate a programmer error: the address of a function always evaluates to true, so their use in
- a conditional usually indicate that the programmer forgot the parentheses in a function call;
- and comparisons against string literals result in unspecified behavior and are not portable in C,
- so they usually indicate that the programmer intended to use "strcmp".
-
- CRITICAL
-
+ 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.
+
]]>
+
+
+
+ -Waddress-of-packed-member
+ Warn when the address of packed member of struct or union is taken
+
+ 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.
+]]>
+
+
-Waggregate-return
Warn about returning structures, unions or arrays
- 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.)
-
- CRITICAL
-
+ 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.)
+]]>
+
+
+
+ -Waggressive-loop-optimizations
+ Warn if a loop with constant number of iterations triggers undefined behavior
+
+ Warn if in a loop with constant number of iterations the compiler detects
+undefined behavior in some statement during one or more of the iterations.
+]]>
+
+
+
+ -Waligned-new
+ Warn about 'new' of type with extended alignment without -faligned-new
+
+ Warn about a new-expression of a type that requires greater alignment
+than the alignof(std::max_align_t)
but uses an allocation
+function without an explicit alignment parameter. This option is
+enabled by -Wall.
+
+Normally this only warns about global allocation functions, but
+-Waligned-new=all also warns about class member allocation
+functions.
+
]]>
+
+
+
+ -Walloc-size
+ Warn when allocating insufficient storage for the target type of the assigned pointer
+
+ Warn about calls to allocation functions decorated with attribute
+alloc_size
that specify insufficient size for the target type of
+the pointer the result is assigned to, including those to the built-in
+forms of the functions aligned_alloc
, alloca
,
+calloc
, malloc
, and realloc
.
+]]>
+
+
+
+ -Walloc-size-larger-than
+ Warn for calls to allocation functions that attempt to allocate objects larger than the specified number of bytes
+
+ Warn about calls to functions decorated with attribute alloc_size
+that attempt to allocate objects larger than the specified number of bytes,
+or where the result of the size computation in an integer type with infinite
+precision would exceed the value of ‘PTRDIFF_MAX’ on the target.
+-Walloc-size-larger-than=‘PTRDIFF_MAX’ is enabled by default.
+Warnings controlled by the option can be disabled either by specifying
+byte-size of ‘SIZE_MAX’ or more or by
+-Wno-alloc-size-larger-than.
+See Declaring Attributes of Functions.
+]]>
+
+
+
+ -Walloc-zero
+ Warn for calls to allocation functions that specify zero bytes
+
+ Warn about calls to allocation functions decorated with attribute
+alloc_size
that specify zero bytes, including those to the built-in
+forms of the functions aligned_alloc
, alloca
, calloc
,
+malloc
, and realloc
. Because the behavior of these functions
+when called with a zero size differs among implementations (and in the case
+of realloc
has been deprecated) relying on it may result in subtle
+portability bugs and should be avoided.
+]]>
+
+
+
+ -Walloca
+ Warn on any use of alloca
+
+ This option warns on all uses of alloca
in the source.
+]]>
+
+
+
+ -Walloca-larger-than
+ Warn on unbounded uses of alloca, and on bounded uses of alloca whose bound can be larger than <number> bytes
+
+ This option warns on calls to alloca
with an integer argument whose
+value is either zero, or that is not bounded by a controlling predicate
+that limits its value to at most byte-size. It also warns for calls
+to alloca
where the bound value is unknown. Arguments of non-integer
+types are considered unbounded even if they appear to be constrained to
+the expected range.
+
+For example, a bounded case of alloca
could be:
+
+
+
void func (size_t n)
+{
+ void *p;
+ if (n <= 1000)
+ p = alloca (n);
+ else
+ p = malloc (n);
+ f (p);
+}
+
+In the above example, passing -Walloca-larger-than=1000
would not
+issue a warning because the call to alloca
is known to be at most
+1000 bytes. However, if -Walloca-larger-than=500
were passed,
+the compiler would emit a warning.
+
+Unbounded uses, on the other hand, are uses of alloca
with no
+controlling predicate constraining its integer argument. For example:
+
+
+
void func ()
+{
+ void *p = alloca (n);
+ f (p);
+}
+
+If -Walloca-larger-than=500
were passed, the above would trigger
+a warning, but this time because of the lack of bounds checking.
+
+Note, that even seemingly correct code involving signed integers could
+cause a warning:
+
+
+
void func (signed int n)
+{
+ if (n < 500)
+ {
+ p = alloca (n);
+ f (p);
+ }
+}
+
+In the above example, n could be negative, causing a larger than
+expected argument to be implicitly cast into the alloca
call.
+
+This option also warns when alloca
is used in a loop.
+
+-Walloca-larger-than=‘PTRDIFF_MAX’ is enabled by default
+but is usually only effective when -ftree-vrp is active (default
+for -O2 and above).
+
+See also -Wvla-larger-than=‘byte-size’.
+
]]>
+
+
- -Waliasing
- Warn about possible aliasing of dummy arguments
+ -Wanalyzer-allocation-size
+ Warn about code paths in which a pointer to a buffer is assigned to an incompatible type
- Warn about possible aliasing of dummy arguments.
-
- CRITICAL
-
+ 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.
+
]]>
+
+
- -Walign-commons
- Warn about alignment of COMMON blocks
+ -Wanalyzer-deref-before-check
+ Warn about code paths in which a pointer is checked for NULL after it has already been dereferenced
- Warn about alignment of COMMON blocks.
-
- CRITICAL
-
+ This warning requires -fanalyzer, which enables it; use
+-Wno-analyzer-deref-before-check
+to disable it.
+
+This diagnostic warns for paths through the code in which a pointer
+is checked for NULL
*after* it has already been
+dereferenced, suggesting that the pointer could have been NULL.
+Such cases suggest that the check for NULL is either redundant,
+or that it needs to be moved to before the pointer is dereferenced.
+
+This diagnostic also considers values passed to a function argument
+marked with __attribute__((nonnull))
as requiring a non-NULL
+value, and thus will complain if such values are checked for NULL
+after returning from such a function call.
+
+This diagnostic is unlikely to be reported when any level of optimization
+is enabled, as GCC’s optimization logic will typically consider such
+checks for NULL as being redundant, and optimize them away before the
+analyzer "sees" them. Hence optimization should be disabled when
+attempting to trigger this diagnostic.
+
]]>
+
+
+
+ -Wanalyzer-double-fclose
+ Warn about code paths in which a stdio FILE can be closed more than once
+
+ This warning requires -fanalyzer, which enables it; use
+-Wno-analyzer-double-fclose to disable it.
+
+This diagnostic warns for paths through the code in which a FILE *
+can have fclose
called on it more than once.
+
+See CWE-1341: Multiple Releases of Same Resource or Handle.
+
]]>
+
+
- -Wampersand
- Warn about missing ampersand in continued character constants
+ -Wanalyzer-double-free
+ Warn about code paths in which a pointer can be freed more than once
- Warn about missing ampersand in continued character constants.
-
- CRITICAL
-
+ This warning requires -fanalyzer, which enables it; use
+-Wno-analyzer-double-free to disable it.
+
+This diagnostic warns for paths through the code in which a pointer
+can have a deallocator called on it more than once, either free
,
+or a deallocator referenced by attribute malloc
.
+
+See CWE-415: Double Free.
+
]]>
+
+
- -Walloc-size-larger-than
- Warn about calls to functions decorated with attribute alloc_size
+ -Wanalyzer-exposure-through-output-file
+ Warn about code paths in which sensitive data is written to a file
- Warn about calls to functions decorated with attribute alloc_size that attempt to allocate objects
- larger than the specified number of bytes, or where the result of the size computation in an
- integer type with infinite precision would exceed SIZE_MAX / 2. The option argument n may end in
- one of the standard suffixes designating a multiple of bytes such as kB and KiB for kilobyte and
- kibibyte, respectively, MB and MiB for megabyte and mebibyte, and so on.
-
- CRITICAL
-
+ This warning requires -fanalyzer, which enables it; use
+-Wno-analyzer-exposure-through-output-file
+to disable it.
+
+This diagnostic warns for paths through the code in which a
+security-sensitive value is written to an output file
+(such as writing a password to a log file).
+
+See CWE-532: Information Exposure Through Log Files.
+
]]>
+
+
- -Walloc-zero
- Warn about calls to allocation functions decorated with attribute alloc_size that specify zero bytes
+ -Wanalyzer-exposure-through-uninit-copy
+ Warn about code paths in which sensitive data is copied across a security boundary
- Warn about calls to allocation functions decorated with attribute alloc_size that specify zero bytes,
- including those to the built-in forms of the functions aligned_alloc, alloca, calloc, malloc, and
- realloc. Because the behavior of these functions when called with a zero size differs among
- implementations (and in the case of realloc has been deprecated) relying on it may result in subtle
- portability bugs and should be avoided.
-
- CRITICAL
-
+ This warning requires both -fanalyzer and the use of a plugin
+to specify a function that copies across a “trust boundary”. Use
+-Wno-analyzer-exposure-through-uninit-copy to disable it.
+
+This diagnostic warns for “infoleaks” - paths through the code in which
+uninitialized values are copied across a security boundary
+(such as code within an OS kernel that copies a partially-initialized
+struct on the stack to user space).
+
+See CWE-200: Exposure of Sensitive Information to an Unauthorized Actor.
+
]]>
+
+
- -Walloca-larger-than
- Warn on calls to alloca that are not bounded by a controlling predicate
+ -Wanalyzer-fd-access-mode-mismatch
+ Warn about code paths in which read on a write-only file descriptor is attempted, or vice versa
- This option warns on calls to alloca that are not bounded by a controlling predicate limiting its
- argument of integer type to at most n bytes, or calls to alloca where the bound is unknown. Arguments
- of non-integer types are considered unbounded even if they appear to be constrained to the expected
- range.
-
- For example, a bounded case of alloca could be:
-
- void func (size_t n)
- {
- void *p;
- if (n <= 1000)
- p = alloca (n);
- else
- p = malloc (n);
- f (p);
- }
-
- In the above example, passing -Walloca-larger-than=1000 would not issue a warning because the call to
- alloca is known to be at most 1000 bytes. However, if -Walloca-larger-than=500 were passed, the
- compiler would emit a warning.
-
- Unbounded uses, on the other hand, are uses of alloca with no controlling predicate constraining its
- integer argument. For example:
-
- void func ()
- {
- void *p = alloca (n);
- f (p);
- }
-
- If -Walloca-larger-than=500 were passed, the above would trigger a warning, but this time because of
- the lack of bounds checking.
-
- Note, that even seemingly correct code involving signed integers could cause a warning:
-
- void func (signed int n)
- {
- if (n < 500)
- {
- p = alloca (n);
- f (p);
- }
- }
-
- In the above example, n could be negative, causing a larger than expected argument to be implicitly cast
- into the alloca call.
-
- This option also warns when alloca is used in a loop.
-
- This warning is not enabled by -Wall, and is only active when -ftree-vrp is active (default for -O2 and above).
-
- See also -Wvla-larger-than=n.
-
-
- CRITICAL
-
+ This warning requires -fanalyzer, which enables it; use
+-Wno-analyzer-fd-access-mode-mismatch
+to disable it.
+
+This diagnostic warns for paths through code in which a
+read
on a write-only file descriptor is attempted, or vice versa.
+
+This diagnostic also warns for code paths in a which a function with attribute
+fd_arg_read (N)
is called with a file descriptor opened with
+O_WRONLY
at referenced argument N
or a function with attribute
+fd_arg_write (N)
is called with a file descriptor opened with
+O_RDONLY
at referenced argument N.
+
]]>
+
+
+
+ -Wanalyzer-fd-double-close
+ Warn about code paths in which a file descriptor can be closed more than once
+
+ 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.
+
]]>
+
+
- -Warray-bounds
- Warn if an array is accessed out of bounds
+ -Wanalyzer-fd-leak
+ Warn about code paths in which a file descriptor is not closed
+
+ 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.
+
]]>
+
+
+
+ -Wanalyzer-fd-phase-mismatch
+ Warn about code paths in which an operation is attempted in the wrong phase of a file descriptor's lifetime
+
+ 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.
+
]]>
+
+
+
+ -Wanalyzer-fd-type-mismatch
+ Warn about code paths in which an operation is attempted on the wrong type of file descriptor
+
+ 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.
+
]]>
+
+
+
+ -Wanalyzer-fd-use-after-close
+ Warn about code paths in which a read or write is performed on a closed file descriptor
+
+ This warning requires -fanalyzer, which enables it; use
+-Wno-analyzer-fd-use-after-close
+to disable it.
+
+This diagnostic warns for paths through code in which a
+read or write is called on a closed file descriptor.
+
+This diagnostic also warns for paths through code in which
+a function with attribute fd_arg (N)
or fd_arg_read (N)
+or fd_arg_write (N)
is called with a closed file descriptor at
+referenced argument N
.
+
]]>
+
+
+
+ -Wanalyzer-fd-use-without-check
+ Warn about code paths in which a file descriptor is used without being checked for validity
+
+ 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.
+
]]>
+
+
+
+ -Wanalyzer-file-leak
+ Warn about code paths in which a stdio FILE is not closed
+
+ 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.
+
]]>
+
+
+
+ -Wanalyzer-free-of-non-heap
+ Warn about code paths in which a non-heap pointer is freed
+
+ 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.
+
]]>
+
+
+
+ -Wanalyzer-imprecise-fp-arithmetic
+ Warn about code paths in which floating-point arithmetic is used in locations where precise computation is needed
+
+ This warning requires -fanalyzer, which enables it; use
+-Wno-analyzer-imprecise-fp-arithmetic
+to disable it.
+
+This diagnostic warns for paths through the code in which floating-point
+arithmetic is used in locations where precise computation is needed. This
+diagnostic only warns on use of floating-point operands inside the
+calculation of an allocation size at the moment.
+
]]>
+
+
+
+ -Wanalyzer-infinite-loop
+ Warn about code paths which appear to lead to an 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
+
+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’).
+
]]>
+
+
+
+ -Wanalyzer-infinite-recursion
+ Warn about code paths which appear to lead to 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.
+
]]>
+
+
+
+ -Wanalyzer-jump-through-null
+ Warn about code paths in which a NULL function pointer is called
+
+ 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.
+
]]>
+
+
+
+ -Wanalyzer-malloc-leak
+ Warn about code paths in which a heap-allocated pointer leaks
+
+ 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.
+
]]>
+
+
+
+ -Wanalyzer-mismatching-deallocation
+ Warn about code paths in which the wrong deallocation function is called
+
+ This warning requires -fanalyzer, which enables it; use
+-Wno-analyzer-mismatching-deallocation
+to disable it.
+
+This diagnostic warns for paths through the code in which the
+wrong deallocation function is called on a pointer value, based on
+which function was used to allocate the pointer value. The diagnostic
+will warn about mismatches between free
, scalar delete
+and vector delete[]
, and those marked as allocator/deallocator
+pairs using attribute malloc
.
+
+See CWE-762: Mismatched Memory Management Routines.
+
]]>
+
+
+
+ -Wanalyzer-null-argument
+ Warn about code paths in which NULL is passed to a must-not-be-NULL function 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.
+
]]>
+
+
+
+ -Wanalyzer-null-dereference
+ Warn about code paths in which a NULL pointer is dereferenced
+
+ 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.
+
]]>
+
+
+
+ -Wanalyzer-out-of-bounds
+ Warn about code paths in which a write or read to a buffer is 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 analyzer is able to determine a constant offset and for
+accesses past the end of a buffer, also a constant capacity. Further,
+the diagnostic does limited checking for accesses past the end when the
+offset as well as the capacity is symbolic.
+
+See CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer.
+
+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.
+
]]>
+
+
+
+ -Wanalyzer-overlapping-buffers
+ Warn about code paths in which undefined behavior would occur due to 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
+strcpy
+
+for cases where the buffers are known to overlap.
+
]]>
+
+
+
+ -Wanalyzer-possible-null-argument
+ Warn about code paths in which a possibly-NULL value is passed to a must-not-be-NULL function 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.
+
]]>
+
+
+
+ -Wanalyzer-possible-null-dereference
+ Warn about code paths in which a possibly-NULL pointer is dereferenced
+
+ 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.
+
]]>
+
+
+
+ -Wanalyzer-putenv-of-auto-var
+ Warn about code paths in which an on-stack buffer is passed to putenv
+
+ 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.
+
]]>
+
+
+
+ -Wanalyzer-shift-count-negative
+ Warn about code paths in which a shift with negative count is attempted
+
+ This warning requires -fanalyzer, which enables it; use
+-Wno-analyzer-shift-count-negative to disable it.
+
+This diagnostic warns for paths through the code in which a
+shift is attempted with a negative count. It is analogous to
+the -Wshift-count-negative diagnostic implemented in
+the C/C++ front ends, but is implemented based on analyzing
+interprocedural paths, rather than merely parsing the syntax tree.
+However, the analyzer does not prioritize detection of such paths, so
+false negatives are more likely relative to other warnings.
+
]]>
+
+
+
+ -Wanalyzer-shift-count-overflow
+ Warn about code paths in which a shift with count >= width of type is attempted
+
+ 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.
+
]]>
+
+
+
+ -Wanalyzer-stale-setjmp-buffer
+ Warn about code paths in which a longjmp rewinds to a jmp_buf saved in a stack frame that has returned
+
+ 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).
+
]]>
+
+
+
+ -Wanalyzer-symbol-too-complex
+ Warn if expressions are too complicated for the analyzer to fully track
+
+ 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-tainted-allocation-size
+ Warn about code paths in which an unsanitized value is used as an 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.
+
]]>
+
+
+
+ -Wanalyzer-tainted-array-index
+ Warn about code paths in which an unsanitized value is used as an 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.
+
]]>
+
+
+
+ -Wanalyzer-tainted-assertion
+ Warn about code paths in which an 'assert()' is made involving an unsanitized value
+
+ This warning requires -fanalyzer which enables it;
+use -Wno-analyzer-tainted-assertion to disable it.
+
+This diagnostic warns for paths through the code in which a value
+that could be under an attacker’s control is used as part of a
+condition without being first sanitized, and that condition guards a
+call to a function marked with attribute noreturn
+(such as the function __builtin_unreachable
). Such functions
+typically indicate abnormal termination of the program, such as for
+assertion failure handlers. For example:
+
+
+
assert (some_tainted_value < SOME_LIMIT);
+
+In such cases:
+
+
+- when assertion-checking is enabled: an attacker could trigger
+a denial of service by injecting an assertion failure
+
+
- when assertion-checking is disabled, such as by defining
NDEBUG
,
+an attacker could inject data that subverts the process, since it
+presumably violates a precondition that is being assumed by the code.
+
+
+Note that when assertion-checking is disabled, the assertions are
+typically removed by the preprocessor before the analyzer has a chance
+to "see" them, so this diagnostic can only generate warnings on builds
+in which assertion-checking is enabled.
+
+For the purpose of this warning, any function marked with attribute
+noreturn
is considered as a possible assertion failure
+handler, including __builtin_unreachable
. Note that these functions
+are sometimes removed by the optimizer before the analyzer "sees" them.
+Hence optimization should be disabled when attempting to trigger this
+diagnostic.
+
+See CWE-617: Reachable Assertion.
+
+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.
+
]]>
+
+
+
+ -Wanalyzer-tainted-divisor
+ Warn about code paths in which an unsanitized value is used as a 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.
+
]]>
+
+
+
+ -Wanalyzer-tainted-offset
+ Warn about code paths in which an unsanitized value is used as a pointer 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.
+
]]>
+
+
+
+ -Wanalyzer-tainted-size
+ Warn about code paths in which an unsanitized value is used as a 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 access.
+
+See CWE-129: Improper Validation of Array Index.
+
]]>
+
+
+
+ -Wanalyzer-too-complex
+ Warn if the code is too complicated for the analyzer to fully explore
+
+ 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.
+
]]>
+
+
+
+ -Wanalyzer-undefined-behavior-strtok
+ Warn about code paths in which a call is made to strtok with undefined behavior
+
+ 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.
+
]]>
+
+
+
+ -Wanalyzer-unsafe-call-within-signal-handler
+ Warn about code paths in which an async-signal-unsafe function is called from a 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.
+
]]>
+
+
+
+ -Wanalyzer-use-after-free
+ Warn about code paths in which a freed value is used
+
+ 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.
+
]]>
+
+
+
+ -Wanalyzer-use-of-pointer-in-stale-stack-frame
+ Warn about code paths in which a pointer to a stale stack frame is used
+
+ This warning requires -fanalyzer, which enables it; use
+-Wno-analyzer-use-of-pointer-in-stale-stack-frame
+to disable it.
+
+This diagnostic warns for paths through the code in which a pointer
+is dereferenced that points to a variable in a stale stack frame.
+
]]>
+
+
+
+ -Wanalyzer-use-of-uninitialized-value
+ Warn about code paths in which an uninitialized value is used
+
+ 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.
+
]]>
+
+
+
+ -Wanalyzer-va-arg-type-mismatch
+ Warn about code paths in which va_arg uses the wrong type
+
+ 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.
+
]]>
+
+
+
+ -Wanalyzer-va-list-exhausted
+ Warn about code paths in which va_arg is used too many times on a va_list
- This option is only active when -ftree-vrp is active (default for -O2 and above). It
- warns about subscripts to arrays that are always out of bounds.
-
- CRITICAL
- BUG
-
+ 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.
+
]]>
+
+
- -Warray-temporaries
- Warn about creation of array temporaries
+ -Wanalyzer-va-list-leak
+ Warn about code paths in which va_start or va_copy is used without a corresponding va_end
- Warn about creation of array temporaries.
-
- CRITICAL
-
+ 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
.
+
]]>
+
+
+
+ -Wanalyzer-va-list-use-after-va-end
+ Warn about code paths in which a va_list is used 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
.
+
]]>
+
+
+
+ -Wanalyzer-write-to-const
+ Warn about code paths which attempt to write to a const object
+
+ 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.
+
]]>
+
+
+
+ -Wanalyzer-write-to-string-literal
+ Warn about code paths which attempt to write to a string literal
+
+ This warning requires -fanalyzer, which enables it; use
+-Wno-analyzer-write-to-string-literal
+to disable it.
+
+This diagnostic warns for paths through the code in which the analyzer
+detects an attempt to write through a pointer to a string literal.
+However, the analyzer does not prioritize detection of such paths, so
+false negatives are more likely relative to other warnings.
+
]]>
+
+
+
+ -Warith-conversion
+ Warn if conversion of the result of arithmetic might change the value even though converting the operands cannot
+
+ Do warn about implicit conversions from arithmetic operations even
+when conversion of the operands to the same type cannot change their
+values. This affects warnings from -Wconversion,
+-Wfloat-conversion, and -Wsign-conversion.
+
+
+
void f (char c, int i)
+{
+ c = c + i; // warns with -Wconversion
+ c = c + 1; // only warns with -Warith-conversion
+}
+
]]>
+
+
+
+ -Warray-bounds
+ Warn if an array is accessed out of bounds
+
+ 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 warning level may
+give a larger number of false positives and is deactivated by default.
+
+
]]>
+
+
+
+ -Warray-compare
+ Warn about comparisons between two operands of array type
+
+ Warn about equality and relational comparisons between two operands of array
+type. This comparison was deprecated in C++20. For example:
+
+
+
int arr1[5];
+int arr2[5];
+bool same = arr1 == arr2;
+
+-Warray-compare is enabled by -Wall.
+
]]>
+
+
+
+ -Warray-parameter
+ Warn about mismatched declarations of array parameters and unsafe accesses to them
+
+ Warn about redeclarations of functions involving parameters of array or
+pointer types of inconsistent kinds or forms, and enable the detection
+of out-of-bounds accesses to such parameters by warnings such as
+-Warray-bounds.
+
+If the first function declaration uses the array form for a parameter
+declaration, the bound specified
+in the array is assumed to be the minimum number of elements expected to
+be provided in calls to the function and the maximum number of elements
+accessed by it. Failing to provide arguments of sufficient size or accessing
+more than the maximum number of elements may be diagnosed by warnings such
+as -Warray-bounds or -Wstringop-overflow.
+At level 1, the warning diagnoses inconsistencies
+involving array parameters declared using the T[static N]
form.
+
+For example, the warning triggers for the second declaration of f
+because the first one with the keyword static
specifies that
+the array argument must have at least four elements, while the second
+allows an array of any size to be passed to f
.
+
+
+
void f (int[static 4]);
+void f (int[]); // warning (inconsistent array form)
+
+void g (void)
+{
+ int *p = (int *)malloc (1 * sizeof (int));
+ f (p); // warning (array too small)
+ …
+}
+
+At level 2 the warning also triggers for redeclarations involving any other
+inconsistency in array or pointer argument forms denoting array sizes.
+Pointers and arrays of unspecified bound are considered equivalent and do
+not trigger a warning.
+
+
+
void g (int*);
+void g (int[]); // no warning
+void g (int[8]); // warning (inconsistent array bound)
+
+-Warray-parameter=2 is included in -Wall. The
+-Wvla-parameter option triggers warnings for similar inconsistencies
+involving Variable Length Array arguments.
+
+The short form of the option -Warray-parameter is equivalent to
+-Warray-parameter=2. The negative form -Wno-array-parameter
+is equivalent to -Warray-parameter=0.
+
]]>
+
+
-Wassign-intercept
Warn whenever an Objective-C assignment is being intercepted by the garbage collector
- Warn whenever an Objective-C assignment is being intercepted by the garbage collector.
-
- CRITICAL
-
+ Warn whenever an Objective-C assignment is being intercepted by the
+garbage collector.
+]]>
+
+
+
+ -Wattribute-alias
+ Warn about type safety and similar errors and mismatches in declarations with alias attributes
+
+ Warn about declarations using the alias
and similar attributes whose
+target is incompatible with the type of the alias.
+See Declaring Attributes of Functions.
+
+
+-Wattribute-alias=1
+The default warning level of the -Wattribute-alias option diagnoses
+incompatibilities between the type of the alias declaration and that of its
+target. Such incompatibilities are typically indicative of bugs.
+
+
+-Wattribute-alias=2
+-
+
At this level -Wattribute-alias also diagnoses cases where
+the attributes of the alias declaration are more restrictive than the
+attributes applied to its target. These mismatches can potentially
+result in incorrect code generation. In other cases they may be
+benign and could be resolved simply by adding the missing attribute to
+the target. For comparison, see the -Wmissing-attributes
+option, which controls diagnostics when the alias declaration is less
+restrictive than the target, rather than more restrictive.
+
+Attributes considered include alloc_align
, alloc_size
,
+cold
, const
, hot
, leaf
, malloc
,
+nonnull
, noreturn
, nothrow
, pure
,
+returns_nonnull
, and returns_twice
.
+
+
+-Wattribute-alias is equivalent to -Wattribute-alias=1.
+This is the default. You can disable these warnings with either
+-Wno-attribute-alias or -Wattribute-alias=0.
+
]]>
+
+
+
+ -Wattribute-warning
+ Warn about uses of __attribute__((warning)) declarations
+
+ Warn about usage of functions (see Declaring Attributes of Functions)
+declared with warning
attribute. By default, this warning is
+enabled. -Wno-attribute-warning can be used to disable the
+warning or -Wno-error=attribute-warning can be used to
+disable the error when compiled with -Werror flag.
+]]>
+
+
-Wattributes
Warn about inappropriate attribute usage
- Warn if an unexpected "__attribute__" is used, such as unrecognized attributes,
- function attributes applied to variables, etc. This will not stop errors for incorrect use of
- supported attributes.
-
- CRITICAL
-
+ Warn if an unexpected __attribute__
is used, such as
+unrecognized attributes, function attributes applied to variables,
+etc. This does not stop errors for incorrect use of supported
+attributes.
+
+Warnings about ill-formed uses of standard attributes are upgraded to
+errors by -pedantic-errors.
+
+Additionally, using -Wno-attributes=, it is possible to suppress
+warnings about unknown scoped attributes (in C++11 and C23). For example,
+-Wno-attributes=vendor::attr disables warning about the following
+declaration:
+
+
+
[[vendor::attr]] void f();
+
+It is also possible to disable warning about all attributes in a namespace
+using -Wno-attributes=vendor:: which prevents warning about both
+of these declarations:
+
+
+
[[vendor::safe]] void f();
+[[vendor::unsafe]] void f2();
+
+Note that -Wno-attributes= does not imply -Wno-attributes.
+
]]>
+
+
-Wbad-function-cast
Warn about casting functions to incompatible types
- Warn whenever a function call is cast to a non-matching type. For example, warn if
- "int malloc()" is cast to "anything *".
-
- CRITICAL
-
+ Warn when a function call is cast to a non-matching type.
+For example, warn if a call to a function returning an integer type
+is cast to a pointer type.
+]]>
+
+
+
+ -Wbidi-chars
+ -Wbidi-chars=[none|unpaired|any|ucn] Warn about UTF-8 bidirectional control characters
+
+ Warn about possibly misleading UTF-8 bidirectional control characters in
+comments, string literals, character constants, and identifiers. Such
+characters can change left-to-right writing direction into right-to-left
+(and vice versa), which can cause confusion between the logical order and
+visual order. This may be dangerous; for instance, it may seem that a piece
+of code is not commented out, whereas it in fact is.
+
+There are three levels of warning supported by GCC. The default is
+-Wbidi-chars=unpaired, which warns about improperly terminated
+bidi contexts. -Wbidi-chars=none turns the warning off.
+-Wbidi-chars=any warns about any use of bidirectional control
+characters.
+
+By default, this warning does not warn about UCNs. It is, however, possible
+to turn on such checking by using -Wbidi-chars=unpaired,ucn or
+-Wbidi-chars=any,ucn. Using -Wbidi-chars=ucn is valid,
+and is equivalent to -Wbidi-chars=unpaired,ucn, if no previous
+-Wbidi-chars=any was specified.
+
]]>
+
+
-Wbool-compare
Warn about boolean expression compared with an integer value different from true/false
- Warn about boolean expression compared with an integer value different from true/false. For instance,
- the following comparison is always false:
-
- int n = 5;
- …
- if ((n > 1) == 2) { … }
-
- This warning is enabled by -Wall.
-
- CRITICAL
-
+ Warn about boolean expression compared with an integer value different from
+true
/false
. For instance, the following comparison is
+always false:
+
+
int n = 5;
+…
+if ((n > 1) == 2) { … }
+
+This warning is enabled by -Wall.
+
]]>
+
+
-Wbool-operation
- Warn about suspicious operations on expressions of a boolean type
+ Warn about certain operations on boolean expressions
- Warn about suspicious operations on expressions of a boolean type. For instance, bitwise
- negation of a boolean is very likely a bug in the program. For C, this warning also warns
- about incrementing or decrementing a boolean, which rarely makes sense. (In C++,
- decrementing a boolean is always invalid. Incrementing a boolean is invalid in C++1z, and
- deprecated otherwise.)
-
- This warning is enabled by -Wall.
-
- CRITICAL
-
+ Warn about suspicious operations on expressions of a boolean type. For
+instance, bitwise negation of a boolean is very likely a bug in the program.
+For C, this warning also warns about incrementing or decrementing a boolean,
+which rarely makes sense. (In C++, decrementing a boolean is always invalid.
+Incrementing a boolean is invalid in C++17, and deprecated otherwise.)
+
+This warning is enabled by -Wall.
+
]]>
+
+
+
+ -Wbuiltin-declaration-mismatch
+ Warn when a built-in function is declared with the wrong signature
+
+ Warn if a built-in function is declared with an incompatible signature
+or as a non-function, or when a built-in function declared with a type
+that does not include a prototype is called with arguments whose promoted
+types do not match those expected by the function. When -Wextra
+is specified, also warn when a built-in function that takes arguments is
+declared without a prototype. The -Wbuiltin-declaration-mismatch
+warning is enabled by default. To avoid the warning include the appropriate
+header to bring the prototypes of built-in functions into scope.
+
+For example, the call to memset
below is diagnosed by the warning
+because the function expects a value of type size_t
as its argument
+but the type of 32
is int
. With -Wextra,
+the declaration of the function is diagnosed as well.
+
+
extern void* memset ();
+void f (void *d)
+{
+ memset (d, '\0', 32);
+}
+
]]>
+
+
-Wbuiltin-macro-redefined
Warn when a built-in preprocessor macro is undefined or redefined
- Warn if certain built-in macros are redefined. This generate warnings for
- redefinition of "__TIMESTAMP__", "__TIME__", "__DATE__", "__FILE__", and "__BASE_FILE__".
-
- CRITICAL
-
+ Warn if certain built-in macros are redefined. This suppresses
+warnings for redefinition of __TIMESTAMP__
, __TIME__
,
+__DATE__
, __FILE__
, and __BASE_FILE__
.
+]]>
+
+
-Wc++-compat
Warn about C constructs that are not in the common subset of C and C++
- Warn about ISO C constructs that are outside of the common subset of ISO C and ISO
- C++, e.g. request for implicit conversion from "void *" to a pointer to non-"void" type.
-
- CRITICAL
-
-
- -Wc++0x-compat
- Warn about C++ constructs whose meaning differs between ISO C++ 1998 and ISO C++ 200x
-
- Warn about C++ constructs whose meaning differs between ISO C++ 1998 and ISO C++ 200x,
- e.g., identifiers in ISO C++ 1998 that will become keywords in ISO C++ 200x.
-
- CRITICAL
-
+ Warn about ISO C constructs that are outside of the common subset of
+ISO C and ISO C++, e.g. request for implicit conversion from
+void *
to a pointer to non-void
type.
+]]>
+
+
-Wc++11-compat
Warn about C++ constructs whose meaning differs between ISO C++ 1998 and ISO C++ 2011
- Warn about C++ constructs whose meaning differs between ISO C++ 1998 and ISO C++ 2011,
- e.g., identifiers in ISO C++ 1998 that are keywords in ISO C++ 2011.
-
- CRITICAL
-
+ Warn about C++ constructs whose meaning differs between ISO C++ 1998
+and ISO C++ 2011, e.g., identifiers in ISO C++ 1998 that are keywords
+in ISO C++ 2011. This warning turns on -Wnarrowing and is
+enabled by -Wall.
+]]>
+
+
- -Wc++14-compat
- Warn about C++ constructs whose meaning differs between ISO C++ 2011 and ISO C++ 2014
+ -Wc++11-extensions
+ Warn about C++11 constructs in code compiled with an older standard
- Warn about C++ constructs whose meaning differs between ISO C++ 2011 and ISO C++ 2014,
- This warning is enabled by -Wall.
-
- CRITICAL
-
+ Warn about C++11 constructs in code being compiled using
+an older C++ standard. Even without this option, some C++11 constructs
+will only be diagnosed if -Wpedantic is used.
+]]>
+
+
- -Wc++1z-compat
- Warn about C++ constructs whose meaning differs between ISO C++ 2014 and the forthoming ISO C++ 2017(?).
+ -Wc++14-compat
+ Warn about C++ constructs whose meaning differs between ISO C++ 2011 and ISO C++ 2014
- Warn about C++ constructs whose meaning differs between ISO C++ 2014 and the forthoming ISO C++ 2017(?).
- This warning is enabled by -Wall.
-
- CRITICAL
-
+ Warn about C++ constructs whose meaning differs between ISO C++ 2011
+and ISO C++ 2014. This warning is enabled by -Wall.
+]]>
+
+
+
+ -Wc++14-extensions
+ Warn about C++14 constructs in code compiled with an older standard
+
+ Warn about C++14 constructs in code being compiled using
+an older C++ standard. Even without this option, some C++14 constructs
+will only be diagnosed if -Wpedantic is used.
+]]>
+
+
+
+ -Wc++17-compat
+ Warn about C++ constructs whose meaning differs between ISO C++ 2014 and ISO C++ 2017
+
+ Warn about C++ constructs whose meaning differs between ISO C++ 2014
+and ISO C++ 2017. This warning is enabled by -Wall.
+]]>
+
+
+
+ -Wc++17-extensions
+ Warn about C++17 constructs in code compiled with an older standard
+
+ Warn about C++17 constructs in code being compiled using
+an older C++ standard. Even without this option, some C++17 constructs
+will only be diagnosed if -Wpedantic is used.
+]]>
+
+
+
+ -Wc++20-compat
+ Warn about C++ constructs whose meaning differs between ISO C++ 2017 and ISO C++ 2020
+
+ Warn about C++ constructs whose meaning differs between ISO C++ 2017
+and ISO C++ 2020. This warning is enabled by -Wall.
+]]>
+
+
+
+ -Wc++20-extensions
+ Warn about C++20 constructs in code compiled with an older standard
+
+ Warn about C++20 constructs in code being compiled using
+an older C++ standard. Even without this option, some C++20 constructs
+will only be diagnosed if -Wpedantic is used.
+]]>
+
+
+
+ -Wc++23-extensions
+ Warn about C++23 constructs in code compiled with an older standard
+
+ Warn about C++23 constructs in code being compiled using
+an older C++ standard. Even without this option, some C++23 constructs
+will only be diagnosed if -Wpedantic is used.
+]]>
+
+
+
+ -Wc++26-extensions
+ Warn about C++26 constructs in code compiled with an older standard
+
+ Warn about C++26 constructs in code being compiled using
+an older C++ standard. Even without this option, some C++26 constructs
+will only be diagnosed if -Wpedantic is used.
+]]>
+
+
+
+ -Wc11-c23-compat
+ Warn about features not present in ISO C11, but present in ISO C23
+
+ Warn about features not present in ISO C11, but present in ISO C23.
+For instance, warn about omitting the string in _Static_assert
,
+use of ‘[[]]’ syntax for attributes, use of decimal
+floating-point types, and so on. This option is independent of the
+standards mode. Warnings are disabled in the expression that follows
+__extension__
. The name -Wc11-c2x-compat is
+deprecated.
+
+When not compiling in C23 mode, these warnings are upgraded to errors
+by -pedantic-errors.
+
]]>
+
+
+
+ -Wc90-c99-compat
+ Warn about features not present in ISO C90, but present in ISO C99
+
+ Warn about features not present in ISO C90, but present in ISO C99.
+For instance, warn about use of variable length arrays, long long
+type, bool
type, compound literals, designated initializers, and so
+on. This option is independent of the standards mode. Warnings are disabled
+in the expression that follows __extension__
.
+]]>
+
+
+
+ -Wc99-c11-compat
+ Warn about features not present in ISO C99, but present in ISO C11
+
+ Warn about features not present in ISO C99, but present in ISO C11.
+For instance, warn about use of anonymous structures and unions,
+_Atomic
type qualifier, _Thread_local
storage-class specifier,
+_Alignas
specifier, Alignof
operator, _Generic
keyword,
+and so on. This option is independent of the standards mode. Warnings are
+disabled in the expression that follows __extension__
.
+]]>
+
+
+
+ -Wcalloc-transposed-args
+ Warn about suspicious calls to calloc-like functions where sizeof expression is the earlier size argument and not the latter
+
+ Warn about calls to allocation functions decorated with attribute
+alloc_size
with two arguments, which use sizeof
operator
+as the earlier size argument and don’t use it as the later size argument.
+This is a coding style warning. The first argument to calloc
is
+documented to be number of elements in array, while the second argument
+is size of each element, so calloc (n, sizeof (int))
is preferred
+over calloc (sizeof (int), n)
. If sizeof
in the earlier
+argument and not the latter is intentional, the warning can be suppressed
+by using calloc (sizeof (struct S) + 0, n)
or
+calloc (1 * sizeof (struct S), 4)
or using sizeof
in the
+later argument as well.
+]]>
+
+
+
+ -Wcannot-profile
+ Warn when profiling instrumentation was requested, but could not be applied to a certain function
+
+
+
+
-Wcast-align
Warn about pointer casts which increase alignment
- 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.
-
- CRITICAL
-
+ 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-function-type
+ Warn about casts between incompatible function types
+
+ 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.
+]]>
+
+
-Wcast-qual
Warn about casts which discard qualifiers
- Warn whenever a pointer is cast so as to remove a type qualifier from the target type.
- For example, warn if a "const char *" is cast to an ordinary "char *".
-
- Also warn when making a cast which introduces a type qualifier in an unsafe way. For example,
- casting "char **" to "const char **" is unsafe, as in this example:
-
- /* p is char ** value. */
- const char **q = (const char **) p;
- /* Assignment of readonly string to const char * is OK. */
- *q = "string";
- /* Now char** pointer points to read-only memory. */
- **p = 'b';
-
- CRITICAL
-
+ Warn whenever a pointer is cast so as to remove a type qualifier from
+the target type. For example, warn if a const char *
is cast
+to an ordinary char *
.
+
+Also warn when making a cast that introduces a type qualifier in an
+unsafe way. For example, casting char **
to const char **
+is unsafe, as in this example:
+
+
+
/* p is char ** value. */
+ const char **q = (const char **) p;
+ /* Assignment of readonly string to const char * is OK. */
+ *q = "string";
+ /* Now char** pointer points to read-only memory. */
+ **p = 'b';
+
]]>
+
+
+
+ -Wcast-user-defined
+ Warn about a cast to reference type that does not use a related user-defined conversion function
+
+ Warn when a cast to reference type does not involve a user-defined
+conversion that the programmer might expect to be called.
+
+
+
struct A { operator const int&(); } a;
+auto r = (int&)a; // warning
+
+This warning is enabled by default.
+
]]>
+
+
-Wcatch-value
- Warn about catch handlers that do not catch via reference.
-
- Warn about catch handlers that do not catch via reference. With -Wcatch-value=1 (or
- -Wcatch-value for short) warn about polymorphic class types that are caught by value.
- With -Wcatch-value=2 warn about all class types that are caught by value. With
- -Wcatch-value=3 warn about all types that are not caught by reference.
-
- -Wcatch-value is enabled by -Wall.
-
- CRITICAL
-
+ Warn about catch handlers of non-reference type
+
+ Warn about catch handlers that do not catch via reference.
+With -Wcatch-value=1 (or -Wcatch-value for short)
+warn about polymorphic class types that are caught by value.
+With -Wcatch-value=2 warn about all class types that are caught
+by value. With -Wcatch-value=3 warn about all types that are
+not caught by reference. -Wcatch-value is enabled by -Wall.
+]]>
+
+
+
+ -Wchanges-meaning
+ Complain about a name being declared as a class member after a previous use of the same name
+
+ C++ requires that unqualified uses of a name within a class have the
+same meaning in the complete scope of the class, so declaring the name
+after using it is ill-formed:
+
+
struct A;
+struct B1 { A a; typedef A A; }; // warning, 'A' changes meaning
+struct B2 { A a; struct A { }; }; // error, 'A' changes meaning
+
+By default, the B1 case is only a warning because the two declarations
+have the same type, while the B2 case is an error. Both diagnostics
+can be disabled with -Wno-changes-meaning. Alternately, the
+error case can be reduced to a warning with
+-Wno-error=changes-meaning or -fpermissive.
+
+Both diagnostics are also suppressed by -fms-extensions.
+
]]>
+
+
-Wchar-subscripts
Warn about subscripts whose type is "char"
- Warn if an array subscript has type "char". This is a common cause of error, as
- programmers often forget that this type is signed on some machines.
-
- CRITICAL
-
+ Warn if an array subscript has type char
. This is a common cause
+of error, as programmers often forget that this type is signed on some
+machines.
+This warning is enabled by -Wall.
+]]>
+
+
- -Wcharacter-truncation
- Warn about truncated character expressions
+ -Wchkp
+ Removed in GCC 9
- Warn about truncated character expressions.
-
- CRITICAL
-
+
+
+
- -Wchkp
- Warn about an invalid memory access that is found by Pointer Bounds Checker (-fcheck-pointer-bounds).
+ -Wclass-conversion
+ Warn when a conversion function will never be called due to the type it converts to
- Warn about an invalid memory access that is found by Pointer Bounds Checker (-fcheck-pointer-bounds).
-
- CRITICAL
-
+ 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.
+]]>
+
+
-Wclass-memaccess
- Warn when the destination of a call to a raw memory function violate const-correctness or encapsulation, or corrupt the virtual table
-
- Warn when the destination of a call to a raw memory function such as memset or memcpy is an object
- of class type writing into which might bypass the class non-trivial or deleted constructor or copy
- assignment, violate const-correctness or encapsulation, or corrupt the virtual table. Modifying
- the representation of such objects may violate invariants maintained by member functions of the
- class. For example, the call to memset below is undefined becase it modifies a non-trivial class
- object and is, therefore, diagnosed. The safe way to either initialize or clear the storage of
- objects of such types is by using the appropriate constructor or assignment operator, if one is
- available.
-
- std::string str = "abc";
- memset (&str, 0, 3);
-
- The -Wclass-memaccess option is enabled by -Wall.
- ]]>
-
- CRITICAL
-
+ Warn for unsafe raw memory writes to objects of class types
+
+ Warn when the destination of a call to a raw memory function such as
+memset
or memcpy
is an object of class type, and when writing
+into such an object might bypass the class non-trivial or deleted constructor
+or copy assignment, violate const-correctness or encapsulation, or corrupt
+virtual table pointers. Modifying the representation of such objects may
+violate invariants maintained by member functions of the class. For example,
+the call to memset
below is undefined because it modifies a non-trivial
+class object and is, therefore, diagnosed. The safe way to either initialize
+or clear the storage of objects of such types is by using the appropriate
+constructor or assignment operator, if one is available.
+
+
std::string str = "abc";
+memset (&str, 0, sizeof str);
+
+The -Wclass-memaccess option is enabled by -Wall.
+Explicitly casting the pointer to the class object to void *
or
+to a type that can be safely accessed by the raw memory function suppresses
+the warning.
+
]]>
+
+
-Wclobbered
Warn about variables that might be changed by "longjmp" or "vfork"
- Warn for variables that might be changed by longjmp or vfork.
-
- CRITICAL
-
+ Warn for variables that might be changed by longjmp
or
+vfork
. This warning is also enabled by -Wextra.
+]]>
+
+
+
+ -Wcomma-subscript
+ Warn about uses of a comma operator within a subscripting expression
+
+ Warn about uses of a comma expression within a subscripting expression.
+This usage was deprecated in C++20 and is going to be removed in C++23.
+However, a comma expression wrapped in ( )
is not deprecated. Example:
+
+
+
void f(int *a, int b, int c) {
+ a[b,c]; // deprecated in C++20, invalid in C++23
+ a[(b,c)]; // OK
+}
+
+In C++23 it is valid to have comma separated expressions in a subscript
+when an overloaded subscript operator is found and supports the right
+number and types of arguments. G++ will accept the formerly valid syntax
+for code that is not valid in C++23 but used to be valid but deprecated
+in C++20 with a pedantic warning that can be disabled with
+-Wno-comma-subscript.
+
+Enabled by default with -std=c++20 unless -Wno-deprecated,
+and with -std=c++23 regardless of -Wno-deprecated.
+
+This warning is upgraded to an error by -pedantic-errors in
+C++23 mode or later.
+
]]>
+
+
-Wcomment
Warn about possibly nested block comments, and C++ comments spanning more than one physical line
- Warn whenever a comment-start sequence /* appears in a /* comment, or whenever a Backslash-Newline
- appears in a // comment.
-
- CRITICAL
-
+ 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.
+]]>
+
+
+
+ -Wcompare-distinct-pointer-types
+ Warn if pointers of distinct types are compared without a cast
+
+ Warn if pointers of distinct types are compared without a cast. This
+warning is enabled by default.
+]]>
+
+
+
+ -Wcomplain-wrong-lang
+ Complain when a command-line option is valid, but not applicable to the current front end
+
+ 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.
+
]]>
+
+
-Wconditionally-supported
- Warn for conditionally-supported (C++11 [intro.defs]) constructs.
+ Warn for conditionally-supported constructs
- Warn for conditionally-supported (C++11 [intro.defs]) constructs.
-
- CRITICAL
-
+ Warn for conditionally-supported (C++11 [intro.defs]) constructs.
+]]>
+
+
-Wconversion
Warn for implicit type conversions that may change a value
- Warn for implicit conversions that may alter a value. This includes conversions
- between real and integer, like "abs (x)" when "x" is "double"; conversions between signed and
- unsigned, like "unsigned ui = -1"; and conversions to smaller types, like "sqrtf (M_PI)". Do not
- warn for explicit casts like "abs ((int) x)" and "ui = (unsigned) -1", or if the value is not
- changed by the conversion like in "abs (2.0)". Warnings about conversions between signed and
- unsigned integers can be disabled by using -Wno-sign-conversion.
-
- For C++, also warn for confusing overload resolution for user-defined conversions; and conversions
- that will 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.
-
- CRITICAL
-
-
- -Wconversion-extra
- Warn about most implicit conversions
-
- Warn about most implicit conversions.
-
- CRITICAL
-
+ Warn for implicit conversions that may alter a value. This includes
+conversions between real and integer, like abs (x)
when
+x
is double
; conversions between signed and unsigned,
+like unsigned ui = -1
; and conversions to smaller types, like
+sqrtf (M_PI)
. Do not warn for explicit casts like abs
+((int) x)
and ui = (unsigned) -1
, or if the value is not
+changed by the conversion like in abs (2.0)
. Warnings about
+conversions between signed and unsigned integers can be disabled by
+using -Wno-sign-conversion.
+
+For C++, also warn for confusing overload resolution for user-defined
+conversions; and conversions that never use a type conversion
+operator: conversions to void
, the same type, a base class or a
+reference to them. Warnings about conversions between signed and
+unsigned integers are disabled by default in C++ unless
+-Wsign-conversion is explicitly enabled.
+
+Warnings about conversion from arithmetic on a small type back to that
+type are only given with -Warith-conversion.
+
]]>
+
+
-Wconversion-null
Warn for converting NULL from/to a non-pointer type
- Warn for conversions between "NULL" and non-pointer types.
-
- CRITICAL
-
+ Warn for conversions between NULL
and non-pointer
+types. -Wconversion-null is enabled by default.
+]]>
+
+
+
+ -Wcoverage-invalid-line-number
+ Warn in case a function ends earlier than it begins due to an invalid linenum macros
+
+ Warn in case a function ends earlier than it begins due
+to an invalid linenum macros. The warning is emitted only
+with --coverage enabled.
+
+By default, this warning is enabled and is treated as an
+error. -Wno-coverage-invalid-line-number can be used to disable the
+warning or -Wno-error=coverage-invalid-line-number can be used to
+disable the error.
+
]]>
+
+
-Wcoverage-mismatch
Warn in case profiles in -fprofile-use do not match
- Warn if feedback profiles do not match when using the -fprofile-use option. If a source
- file was changed between -fprofile-gen and -fprofile-use, the files with the profile feedback can
- fail to match the source file and GCC can not use the profile feedback information. By default,
- this warning is enabled and is treated as an error. -Wno-coverage-mismatch can be used to disable
- the warning or -Wno-error=coverage-mismatch can be used to disable the error. Disable the error
- for this warning can result in poorly optimized code, so disabling the error is useful only in the
- case of very minor changes such as bug fixes to an existing code-base. Completely disabling the
- warning is not recommended.
-
- CRITICAL
-
+ Warn if feedback profiles do not match when using the
+-fprofile-use option.
+If a source file is changed between compiling with -fprofile-generate
+and with -fprofile-use, the files with the profile feedback can fail
+to match the source file and GCC cannot use the profile feedback
+information. By default, this warning is enabled and is treated as an
+error. -Wno-coverage-mismatch can be used to disable the
+warning or -Wno-error=coverage-mismatch can be used to
+disable the error. Disabling the error for this warning can result in
+poorly optimized code and is useful only in the
+case of very minor changes such as bug fixes to an existing code-base.
+Completely disabling the warning is not recommended.
+]]>
+
+
+
+ -Wcoverage-too-many-conditions
+ Warn when a conditional has too many terms and condition coverage profiling gives up instrumenting the expression
+
+ Warn if -fcondition-coverage is used and an expression have too many
+terms and GCC gives up coverage. Coverage is given up when there are more
+terms in the conditional than there are bits in a gcov_type_unsigned
.
+This warning is enabled by default.
+]]>
+
+
-Wcpp
Warn when a #warning directive is encountered
- Warning messages emitted by "#warning" directives.
-
- CRITICAL
-
+ Suppress warning messages emitted by #warning
directives.
+]]>
+
+
+
+ -Wctad-maybe-unsupported
+ Warn when performing class template argument deduction on a type with no deduction guides
+
+ Warn when performing class template argument deduction (CTAD) on a type with
+no explicitly written deduction guides. This warning will point out cases
+where CTAD succeeded only because the compiler synthesized the implicit
+deduction guides, which might not be what the programmer intended. Certain
+style guides allow CTAD only on types that specifically "opt-in"; i.e., on
+types that are designed to support CTAD. This warning can be suppressed with
+the following pattern:
+
+
+
struct allow_ctad_t; // any name works
+template <typename T> struct S {
+ S(T) { }
+};
+// Guide with incomplete parameter type will never be considered.
+S(allow_ctad_t) -> S<void>;
+
]]>
+
+
-Wctor-dtor-privacy
Warn when all constructors and destructors are private
- Warn when a class seems unusable because all the constructors or destructors in that
- class are private, and it has neither friends nor public static member functions.
-
- CRITICAL
-
+ Warn when a class seems unusable because all the constructors or
+destructors in that class are private, and it has neither friends nor
+public static member functions. Also warn if there are no non-private
+methods, and there’s at least one private member function that isn’t
+a constructor or destructor.
+]]>
+
+
-Wdangling-else
- Warn about constructions where there may be confusion to which if statement an else branch belongs.
+ Warn about dangling 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)
+ Warn about constructions where there may be confusion to which
+if
statement an else
branch belongs. Here is an example of
+such a case:
+
+
+
{
+ if (a)
+ if (b)
foo ();
- else
- bar ();
- }
-
- In C/C++, every else branch belongs to the innermost possible if statement, which in this
- example is if (b). This is often not what the programmer expected, as illustrated in the
- above example by indentation the programmer chose. When there is the potential for this
- confusion, GCC issues a warning when this flag is specified. To eliminate the warning, add
- explicit braces around the innermost if statement so there is no way the else can belong
- to the enclosing if. The resulting code looks like this:
-
- {
- if (a)
- {
+ else
+ bar ();
+}
+
+In C/C++, every else
branch belongs to the innermost possible
+if
statement, which in this example is if (b)
. This is
+often not what the programmer expected, as illustrated in the above
+example by indentation the programmer chose. When there is the
+potential for this confusion, GCC issues a warning when this flag
+is specified. To eliminate the warning, add explicit braces around
+the innermost if
statement so there is no way the else
+can belong to the enclosing if
. The resulting code
+looks like this:
+
+
+
{
+ if (a)
+ {
if (b)
- foo ();
+ foo ();
else
- bar ();
- }
- }
-
- This warning is enabled by -Wparentheses.
-
- CRITICAL
-
+ bar ();
+ }
+}
+
+This warning is enabled by -Wparentheses.
+
]]>
+
+
+
+ -Wdangling-pointer
+ Warn for uses of pointers to auto variables whose lifetime has ended
+
+ Warn about uses of pointers (or C++ references) to objects with automatic
+storage duration after their lifetime has ended. This includes local
+variables declared in nested blocks, compound literals and other unnamed
+temporary objects. In addition, warn about storing the address of such
+objects in escaped pointers. The warning is enabled at all optimization
+levels but may yield different results with optimization than without.
+
+
+-Wdangling-pointer=1
+At level 1, the warning diagnoses only unconditional uses of dangling pointers.
+
+
+-Wdangling-pointer=2
+At level 2, in addition to unconditional uses the warning also diagnoses
+conditional uses of dangling pointers.
+
+
+The short form -Wdangling-pointer is equivalent to
+-Wdangling-pointer=2, while -Wno-dangling-pointer and
+-Wdangling-pointer=0 have the same effect of disabling the warnings.
+-Wdangling-pointer=2 is included in -Wall.
+
+This example triggers the warning at level 1; the address of the unnamed
+temporary is unconditionally referenced outside of its scope.
+
+
+
char f (char c1, char c2, char c3)
+{
+ char *p;
+ {
+ p = (char[]) { c1, c2, c3 };
+ }
+ // warning: using dangling pointer 'p' to an unnamed temporary
+ return *p;
+}
+
+In the following function the store of the address of the local variable
+x
in the escaped pointer *p
triggers the warning at
+level 1.
+
+
+
void g (int **p)
+{
+ int x = 7;
+ // warning: storing the address of local variable 'x' in '*p'
+ *p = &x;
+}
+
+In this example, the array a is out of
+scope when the pointer s is used. Since the code that sets s
+is conditional, the warning triggers at level 2.
+
+
+
extern void frob (const char *);
+void h (char *s)
+{
+ if (!s)
+ {
+ char a[12] = "tmpname";
+ s = a;
+ }
+ // warning: dangling pointer 's' to 'a' may be used
+ frob (s);
+}
+
]]>
+
+
+
+ -Wdangling-reference
+ Warn when a reference is bound to a temporary whose lifetime has ended
+
+ Warn when a reference is bound to a temporary whose lifetime has ended.
+For example:
+
+
+
int n = 1;
+const int& r = std::max(n - 1, n + 1); // r is dangling
+
+In the example above, two temporaries are created, one for each
+argument, and a reference to one of the temporaries is returned.
+However, both temporaries are destroyed at the end of the full
+expression, so the reference r
is dangling. This warning
+also detects dangling references in member initializer lists:
+
+
+
const int& f(const int& i) { return i; }
+struct S {
+ const int &r; // r is dangling
+ S() : r(f(10)) { }
+};
+
+Member functions are checked as well, but only their object argument:
+
+
+
struct S {
+ const S& self () { return *this; }
+};
+const S& s = S().self(); // s is dangling
+
+Certain functions are safe in this respect, for example std::use_facet
:
+they take and return a reference, but they don’t return one of its arguments,
+which can fool the warning. Such functions can be excluded from the warning
+by wrapping them in a #pragma
:
+
+
+
#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-reference"
+const T& foo (const T&) { … }
+#pragma GCC diagnostic pop
+
+The #pragma
can also surround the class; in that case, the warning
+will be disabled for all the member functions.
+
+-Wdangling-reference also warns about code like
+
+
+
auto p = std::minmax(1, 2);
+
+where std::minmax
returns std::pair<const int&, const int&>
, and
+both references dangle after the end of the full expression that contains
+the call to std::minmax
.
+
+The warning does not warn for std::span
-like classes. We consider
+classes of the form:
+
+
+
template<typename T>
+struct Span {
+ T* data_;
+ std::size len_;
+};
+
+as std::span
-like; that is, the class is a non-union class
+that has a pointer data member and a trivial destructor.
+
+The warning can be disabled by using the gnu::no_dangling
attribute
+(see C++-Specific Variable, Function, and Type Attributes).
+
+This warning is enabled by -Wall.
+
]]>
+
+
-Wdate-time
- Warn when macros __TIME__, __DATE__ or __TIMESTAMP__ are encountered
+ Warn about __TIME__, __DATE__ and __TIMESTAMP__ usage
- Warn when macros __TIME__, __DATE__ or __TIMESTAMP__ are encountered as they might prevent
- bit-wise-identical reproducible compilations.
-
- CRITICAL
-
+ Warn when macros __TIME__
, __DATE__
or __TIMESTAMP__
+are encountered as they might prevent bit-wise-identical reproducible
+compilations.
+]]>
+
+
-Wdeclaration-after-statement
Warn when a declaration is found after a statement
- Warn when a declaration is found after a statement in a block. This construct, known
- from C++, was introduced with ISO C99 and is by default allowed in GCC. It is not supported by
- ISO C90 and was not supported by GCC versions before GCC 3.0.
-
- CRITICAL
-
+ Warn when a declaration is found after a statement in a block. This
+construct, known from C++, was introduced with ISO C99 and is by default
+allowed in GCC. It is not supported by ISO C90. See Mixed Declarations, Labels and Code.
+
+This warning is upgraded to an error by -pedantic-errors.
+
]]>
+
+
+
+ -Wdeclaration-missing-parameter-type
+ Warn for missing parameter types in function declarations
+
+ 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.
+
]]>
+
+
-Wdelete-incomplete
Warn when deleting a pointer to incomplete type
- Warn when deleting a pointer to incomplete type, which may cause undefined behavior at runtime.
-
- CRITICAL
-
+ Warn when deleting a pointer to incomplete type, which may cause
+undefined behavior at runtime. This warning is enabled by default.
+]]>
+
+
-Wdelete-non-virtual-dtor
Warn about deleting polymorphic objects with non-virtual destructors
- 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.
-
- CRITICAL
-
+ 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
- Warn about usage of deprecated features
+ Warn if a deprecated compiler feature, class, method, or field is used
+
+ Warn about usage of deprecated features. See Deprecated Features.
+]]>
+
+
+
+ -Wdeprecated-copy
+ Mark implicitly-declared copy operations as deprecated if the class has a user-provided copy operation
+
+ 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.
+]]>
+
+
+
+ -Wdeprecated-copy-dtor
+ Mark implicitly-declared copy operations as deprecated if the class has a user-provided copy operation or destructor
- Warn if a deprecated compiler feature, class, method, or field is used.
-
- CRITICAL
-
+
+
+
-Wdeprecated-declarations
Warn about uses of __attribute__((deprecated)) declarations
- Warn about uses of functions, variables, and types marked as deprecated by using the
- "deprecated" attribute.
-
- CRITICAL
-
+ Warn about uses of functions (see Declaring Attributes of Functions),
+variables (see Specifying Attributes of Variables), and types (see Specifying Attributes of Types) marked as deprecated by using the deprecated
+attribute.
+]]>
+
+
+
+ -Wdeprecated-enum-enum-conversion
+ Warn about deprecated arithmetic conversions on operands of enumeration types
+
+ Disable the warning about the case when the usual arithmetic conversions
+are applied on operands where one is of enumeration type and the other is
+of a different enumeration type. This conversion was deprecated in C++20.
+For example:
+
+
+
enum E1 { e };
+enum E2 { f };
+int k = f - e;
+
+-Wdeprecated-enum-enum-conversion is enabled by default with
+-std=c++20. In pre-C++20 dialects, this warning can be enabled
+by -Wenum-conversion.
+
]]>
+
+
+
+ -Wdeprecated-enum-float-conversion
+ Warn about deprecated arithmetic conversions on operands where one is of enumeration type and the other is of a floating-point type
+
+ Disable the warning about the case when the usual arithmetic conversions
+are applied on operands where one is of enumeration type and the other is
+of a floating-point type. This conversion was deprecated in C++20. For
+example:
+
+
+
enum E1 { e };
+enum E2 { f };
+bool b = e <= 3.7;
+
+-Wdeprecated-enum-float-conversion is enabled by default with
+-std=c++20. In pre-C++20 dialects, this warning can be enabled
+by -Wenum-conversion.
+
]]>
+
+
+
+ -Wdesignated-init
+ Warn about positional initialization of structs requiring designated initializers
+
+ Suppress warnings when a positional initializer is used to initialize
+a structure that has been marked with the designated_init
+attribute.
+]]>
+
+
-Wdisabled-optimization
Warn when an optimization pass is disabled
- Warn if a requested optimization pass is disabled. This warning does not generally
- indicate that there is anything wrong with your code; it merely indicates that GCC's optimizers
- were unable to handle the code effectively. Often, the problem is that your code is too big or
- too complex; GCC will refuse to optimize programs when the optimization itself is likely to take
- inordinate amounts of time.
-
- CRITICAL
-
+ Warn if a requested optimization pass is disabled. This warning does
+not generally indicate that there is anything wrong with your code; it
+merely indicates that GCC’s optimizers are unable to handle the code
+effectively. Often, the problem is that your code is too big or too
+complex; GCC refuses to optimize programs when the optimization
+itself is likely to take inordinate amounts of time.
+]]>
+
+
+
+ -Wdiscarded-array-qualifiers
+ Warn if qualifiers on arrays which are pointer targets are discarded
+
+ 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.
+]]>
+
+
+
+ -Wdiscarded-qualifiers
+ Warn if type qualifiers on pointers are discarded
+
+ 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.
+]]>
+
+
-Wdiv-by-zero
Warn about compile-time integer division by zero
- Warn about compile-time integer division by zero. Floating point division by zero is
- not warned about, as it can be a legitimate way of obtaining infinities and NaNs.
-
- CRITICAL
- BUG
-
+ Warn about compile-time integer division by zero. Floating-point
+division by zero is not warned about, as it can be a legitimate way of
+obtaining infinities and NaNs.
+]]>
+
+
-Wdouble-promotion
Warn about implicit conversions from "float" to "double"
- Give a warning when a value of type "float" is implicitly promoted to "double". CPUs
- with a 32-bit "single-precision" floating-point unit implement "float" in hardware, but emulate
- "double" in software. On such a machine, doing computations using "double" values is much more
- expensive because of the overhead required for software emulation.
-
- It is easy to accidentally do computations with "double" because floating-point literals are
- implicitly of type "double". For example, in:
-
- float area(float radius)
- {
- return 3.14159 * radius * radius;
- }
-
- the compiler will perform the entire computation with "double" because the floating-point literal
- is a "double".
-
- CRITICAL
-
+ Give a warning when a value of type float
is implicitly
+promoted to double
. CPUs with a 32-bit “single-precision”
+floating-point unit implement float
in hardware, but emulate
+double
in software. On such a machine, doing computations
+using double
values is much more expensive because of the
+overhead required for software emulation.
+
+It is easy to accidentally do computations with double
because
+floating-point literals are implicitly of type double
. For
+example, in:
+
+
float area(float radius)
+{
+ return 3.14159 * radius * radius;
+}
+
+the compiler performs the entire computation with double
+because the floating-point literal is a double
.
+
]]>
+
+
-Wduplicate-decl-specifier
- Warn if a declaration has duplicate const, volatile, restrict or _Atomic specifier.
+ Warn when a declaration has duplicate const, volatile, restrict or _Atomic specifier
- Warn if a declaration has duplicate const, volatile, restrict or _Atomic specifier.
-
- CRITICAL
-
+ Warn if a declaration has duplicate const
, volatile
,
+restrict
or _Atomic
specifier. This warning is enabled by
+-Wall.
+]]>
+
+
-Wduplicated-branches
- Warn when an if-else has identical 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;
-
-
- CRITICAL
-
+ Warn about duplicated branches in if-else statements
+
+ 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:
+
]]>
+
+
-Wduplicated-cond
Warn about duplicated conditions in an if-else-if chain
- 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) { … }
-
-
- CRITICAL
-
+ 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) { … }
+
]]>
+
+
-Weffc++
Warn about violations of Effective C++ style rules
- Warn about violations of the following style guidelines from Scott Meyers' Effective
- C++, Second Edition book:
- * Item 11: Define a copy constructor and an assignment operator for classes with dynamically allocated memory.
- * Item 12: Prefer initialization to assignment in constructors.
- * Item 14: Make destructors virtual in base classes.
- * Item 15: Have "operator=" return a reference to *this.
- * Item 23: Don't try to return a reference when you must return an object.
-
- Also warn about violations of the following style guidelines from Scott Meyers' More Effective C++ book:
- * Item 6: Distinguish between prefix and postfix forms of increment and decrement operators.
- * Item 7: Never overload "&&", "||", or ",".
-
- CRITICAL
-
+ Warn about violations of the following style guidelines from Scott Meyers’
+Effective C++ series of books:
+
+
+- Define a copy constructor and an assignment operator for classes
+with dynamically-allocated memory.
+
+
- Prefer initialization to assignment in constructors.
+
+
- Have
operator=
return a reference to *this
.
+
+ - Don’t try to return a reference when you must return an object.
+
+
- Distinguish between prefix and postfix forms of increment and
+decrement operators.
+
+
- Never overload
&&
, ||
, or ,
.
+
+
+This option also enables -Wnon-virtual-dtor, which is also
+one of the effective C++ recommendations. However, the check is
+extended to warn about the lack of virtual destructor in accessible
+non-polymorphic bases classes too.
+
+When selecting this option, be aware that the standard library
+headers do not obey all of these guidelines; use ‘grep -v’
+to filter out those warnings.
+
]]>
+
+
+
+ -Welaborated-enum-base
+ Warn if an additional enum-base is used in an elaborated-type-specifier
+
+ For C++11 and above, warn if an (invalid) additional enum-base is used
+in an elaborated-type-specifier. That is, if an enum with given
+underlying type and no enumerator list is used in a declaration other
+than just a standalone declaration of the enum. Enabled by default. This
+warning is upgraded to an error with -pedantic-errors.
+]]>
+
+
-Wempty-body
Warn about an empty body in an if or else statement
- Warn if an empty body occurs in an if, else or do while statement.
-
- CRITICAL
-
+ Warn if an empty body occurs in an if
, else
or do
+while
statement. This warning is also enabled by -Wextra.
+]]>
+
+
-Wendif-labels
- Warn about stray tokens after #elif and #endif
+ Warn about stray tokens after #else and #endif
- Warn whenever an #else or an #endif are followed by text.
-
- CRITICAL
-
+ 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.
+
]]>
+
+
-Wenum-compare
Warn about comparison of different enum types
- Warn about a comparison between values of different enum types. In C++ this warning
- is enabled by default.
-
- CRITICAL
-
+ 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 about implicit conversion of enum types
+
+ 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
+ Warn about enum/integer type mismatches
+
+ 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.
+
]]>
+
+
+
+ -Wexceptions
+ Warn when an exception handler is shadowed by another handler
+
+ Disable the warning about the case when an exception handler is shadowed by
+another handler, which can point out a wrong ordering of exception handlers.
+]]>
+
+
-Wexpansion-to-defined
- Warn whenever ‘defined’ is encountered in the expansion of a macro
+ Warn if "defined" is used outside #if
+
+ 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.
+]]>
+
+
+
+ -Wextra
+ Print extra (possibly unwanted) warnings
- 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.
+ The option -Wextra also prints warning messages for the
+following cases:
+
+
+- A pointer is compared against integer zero with
<
, <=
,
+>
, or >=
.
+
+ - (C++ only) An enumerator and a non-enumerator both appear in a
+conditional expression.
+
+
- (C++ only) Ambiguous virtual bases.
+
+
- (C++ only) Subscripting an array that has been declared
register
.
+
+ - (C++ only) Taking the address of a variable that has been declared
+
register
.
- This warning is also enabled by -Wpedantic and -Wextra.
-
- CRITICAL
-
+(C++ only) A base class is not initialized in the copy constructor
+of a derived class.
+
+]]>
+
+
+
+ -Wextra-semi
+ Warn about semicolon after in-class function definition
+
+ Warn about redundant semicolons after in-class function definitions.
+]]>
+
+
+
+ -Wflex-array-member-not-at-end
+ Warn when a structure containing a C99 flexible array member as the last field is not at the end of another structure
+
+ 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.
+ Warn for implicit type conversions that cause loss of floating point precision
- 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.
-
- CRITICAL
-
+ 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.
+]]>
+
+
-Wfloat-equal
Warn if testing floating point numbers for equality
- 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 would 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.
-
- CRITICAL
-
+ 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.
+
]]>
+
+
-Wformat
Warn about printf/scanf/strftime/strfmon format string anomalies
- Check calls to "printf" and "scanf", etc., to make sure that the arguments supplied
- have types appropriate to the format string specified, and that the conversions specified in the
- format string make sense. This includes standard functions, and others specified by format
- attributes, in the "printf", "scanf", "strftime" and "strfmon" (an X/Open extension, not in the C
- standard) families (or other target-specific families). Which functions are checked without format
- attributes having been specified depends on the standard version selected, and such checks of
- functions without the attribute specified are disabled by -ffreestanding or -fno-builtin.
-
- The formats are checked against the format features supported by GNU libc version 2.2. These
- include all ISO C90 and C99 features, as well as features from the Single Unix Specification and
- some BSD and GNU extensions. Other library implementations may not support all these features;
- GCC does not support warning about features that go beyond a particular library's limitations.
- However, if -pedantic is used with -Wformat, warnings will be given about format features not in
- the selected standard version (but not for "strfmon" formats, since those are not in any version
- of the C standard).
-
- CRITICAL
-
+ Check calls to printf
and scanf
, etc., to make sure that
+the arguments supplied have types appropriate to the format string
+specified, and that the conversions specified in the format string make
+sense. This includes standard functions, and others specified by format
+attributes (see Declaring Attributes of Functions), in the printf
,
+scanf
, strftime
and strfmon
(an X/Open extension,
+not in the C standard) families (or other target-specific families).
+Which functions are checked without format attributes having been
+specified depends on the standard version selected, and such checks of
+functions without the attribute specified are disabled by
+-ffreestanding or -fno-builtin.
+
+The formats are checked against the format features supported by GNU
+libc version 2.2. These include all ISO C90 and C99 features, as well
+as features from the Single Unix Specification and some BSD and GNU
+extensions. Other library implementations may not support all these
+features; GCC does not support warning about features that go beyond a
+particular library’s limitations. However, if -Wpedantic is used
+with -Wformat, warnings are given about format features not
+in the selected standard version (but not for strfmon
formats,
+since those are not in any version of the C standard). See Options Controlling C Dialect.
+
+
+-
+
-Wformat=1
¶
+-Wformat
+Option -Wformat is equivalent to -Wformat=1, and
+-Wno-format is equivalent to -Wformat=0. Since
+-Wformat also checks for null format arguments for several
+functions, -Wformat also implies -Wnonnull. Some
+aspects of this level of format checking can be disabled by the
+options: -Wno-format-contains-nul,
+-Wno-format-extra-args, and -Wno-format-zero-length.
+-Wformat is enabled by -Wall.
+
+
+-Wformat=2
¶
+Enable -Wformat plus additional format checks. Currently
+equivalent to -Wformat -Wformat-nonliteral -Wformat-security
+-Wformat-y2k.
+
+
]]>
+
+
-Wformat-contains-nul
Warn about format strings that contain NUL bytes
- Warn about format strings that contain NUL bytes.
-
- CRITICAL
-
+ If -Wformat is specified, do not warn about format strings that
+contain NUL bytes.
+]]>
+
+
+
+ -Wformat-diag
+ Warn about GCC format strings with strings unsuitable for diagnostics
+
+
+
+
-Wformat-extra-args
Warn if passing too many arguments to a function for its format string
- 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 will suppress the warning if the unused arguments are all pointers, since the Single
- Unix Specification says that such unused arguments are allowed.
-
- CRITICAL
-
+ If -Wformat is specified, do not warn about excess arguments to a
+printf
or scanf
format function. The C standard specifies
+that such arguments are ignored.
+
+Where the unused arguments lie between used arguments that are
+specified with ‘$’ operand number specifications, normally
+warnings are still given, since the implementation could not know what
+type to pass to va_arg
to skip the unused arguments. However,
+in the case of scanf
formats, this option suppresses the
+warning if the unused arguments are all pointers, since the Single
+Unix Specification says that such unused arguments are allowed.
+
]]>
+
+
-Wformat-nonliteral
Warn about format strings that are not literals
- 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".
-
- CRITICAL
-
+ 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-overflow
- Warn about calls to formatted input/output functions that might overflow the destination buffer
-
- 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 directives with unknown values are assumed to have the value of
- one, and strings of unknown length to be empty. Numeric arguments that are known to
- be bounded to a subrange of their type, or string arguments whose output is bounded
- either by their directive’s precision or by a finite set of string literals, are
- assumed to take on the value within the range that results in the most bytes on
- output. For example, the call to sprintf below is diagnosed because even with both
- a and b equal to zero, the terminating NUL character ('\0') appended by the function
- to the destination buffer will be written past its end. Increasing the size of the
- buffer by a single byte is sufficient to avoid the warning, though it may not be
- sufficient to avoid the overflow.
-
- void f (int a, int b)
- {
- char buf [12];
- 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
- arguments whose length cannot be assumed to be bounded either by the directive’s
- precision, or by a finite set of string literals they may evaluate to, or the
- character array they may point to, are assumed to be 1 character long.
-
- At level 2, the call in the example above is again diagnosed, but this time because
- with a equal to a 32-bit INT_MIN the first %i directive will write some of its digits
- beyond the end of the destination buffer. To make the call safe regardless of the
- values of the two variables, the size of the destination buffer must be increased to
- at least 34 bytes. GCC includes the minimum size of the buffer in an informational
- note following the warning.
-
- An alternative to increasing the size of the destination buffer is to constrain the
- range of formatted values. The maximum length of string arguments can be bounded by
- specifying the precision in the format directive. When numeric arguments of format
- directives can be assumed to be bounded by less than the precision of their type,
- choosing an appropriate length modifier to the format specifier will reduce the
- required buffer size. For example, if a and b in the example above can be assumed to
- be within the precision of the short int type then using either the %hi format
- directive or casting the argument to short reduces the maximum required size of the
- buffer to 24 bytes.
-
- void f (int a, int b)
- {
- char buf [23];
- sprintf (buf, "a = %hi, b = %i\n", a, (short)b);
- }
-
-
- CRITICAL
-
+ Warn about function calls with format strings that write past the end of the destination region
+
+ 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
+directives with unknown values are assumed to have the value of one, and
+strings of unknown length to be empty. Numeric arguments that are known
+to be bounded to a subrange of their type, or string arguments whose output
+is bounded either by their directive’s precision or by a finite set of
+string literals, are assumed to take on the value within the range that
+results in the most bytes on output. For example, the call to sprintf
+below is diagnosed because even with both a and b equal to zero,
+the terminating NUL character ('\0'
) appended by the function
+to the destination buffer will be written past its end. Increasing
+the size of the buffer by a single byte is sufficient to avoid the
+warning, though it may not be sufficient to avoid the overflow.
+
+
+
void f (int a, int b)
+{
+ char buf [13];
+ sprintf (buf, "a = %i, b = %i\n", a, b);
+}
+
+
+-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 arguments whose
+length cannot be assumed to be bounded either by the directive’s precision,
+or by a finite set of string literals they may evaluate to, or the character
+array they may point to, are assumed to be 1 character long.
+
+At level 2, the call in the example above is again diagnosed, but
+this time because with a equal to a 32-bit INT_MIN
the first
+%i
directive will write some of its digits beyond the end of
+the destination buffer. To make the call safe regardless of the values
+of the two variables, the size of the destination buffer must be increased
+to at least 34 bytes. GCC includes the minimum size of the buffer in
+an informational note following the warning.
+
+An alternative to increasing the size of the destination buffer is to
+constrain the range of formatted values. The maximum length of string
+arguments can be bounded by specifying the precision in the format
+directive. When numeric arguments of format directives can be assumed
+to be bounded by less than the precision of their type, choosing
+an appropriate length modifier to the format specifier will reduce
+the required buffer size. For example, if a and b in the
+example above can be assumed to be within the precision of
+the short int
type then using either the %hi
format
+directive or casting the argument to short
reduces the maximum
+required size of the buffer to 24 bytes.
+
+
+
void f (int a, int b)
+{
+ char buf [23];
+ sprintf (buf, "a = %hi, b = %i\n", a, (short)b);
+}
+
+
+
]]>
+
+
-Wformat-security
Warn about possible security problems with format functions
- Warn about uses of format functions that represent possible security problems. At
- present, this warns about calls to "printf" and "scanf" functions where the format string is not
- a string literal and there are no format arguments, as in "printf (foo);". This may be a security
- hole if the format string came from untrusted input and contains %n.
-
- CRITICAL
-
+ If -Wformat is specified, also warn about uses of format
+functions that represent possible security problems. At present, this
+warns about calls to printf
and scanf
functions where the
+format string is not a string literal and there are no format arguments,
+as in printf (foo);
. This may be a security hole if the format
+string came from untrusted input and contains ‘%n’. (This is
+currently a subset of what -Wformat-nonliteral warns about, but
+in future warnings may be added to -Wformat-security that are not
+included in -Wformat-nonliteral.)
+]]>
+
+
-Wformat-signedness
- Warn if the format string requires an unsigned argument and the argument is signed and vice versa.
+ Warn about sign differences with format functions
- If -Wformat is specified, also warn if the format string requires an unsigned argument and the
- argument is signed and vice versa.
-
- CRITICAL
-
+ If -Wformat is specified, also warn if the format string
+requires an unsigned argument and the argument is signed and vice versa.
+]]>
+
+
-Wformat-truncation
- Warn about calls to formatted input/output functions that might result in output truncation
-
- 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.
-
- CRITICAL
-
+ Warn about calls to snprintf and similar functions that truncate output
+
+ 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
Warn about strftime formats yielding 2-digit years
- Warn about "strftime" formats which may yield only a two-digit year.
-
- CRITICAL
-
+ If -Wformat is specified, also warn about strftime
+formats that may yield only a two-digit year.
+]]>
+
+
-Wformat-zero-length
Warn about zero-length formats
- Warn about zero-length formats. The C standard specifies that zero-length formats are
- allowed.
-
- CRITICAL
-
+ If -Wformat is specified, do not warn about zero-length formats.
+The C standard specifies that zero-length formats are allowed.
+]]>
+
+
-Wframe-address
- Warn when the ‘__builtin_frame_address’ or ‘__builtin_return_address’ is called with an argument greater than 0
+ Warn when __builtin_frame_address or __builtin_return_address is used unsafely
- 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.
-
- CRITICAL
-
+ 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.
+]]>
+
+
-Wframe-larger-than
- Warn about large frames
-
- Warn if the size of a function frame is larger than len bytes. The computation done
- to determine the stack frame size is approximate and not conservative. The actual requirements
- may be somewhat greater than len even if you do not get a warning. In addition, any space allocated
- via "alloca", variable-length arrays, or related constructs is not included by the compiler when
- determining whether or not to issue a warning.
-
- CRITICAL
-
+ Warn if a function's stack frame requires in excess of <byte-size>
+
+ Warn if the size of a function frame exceeds byte-size.
+The computation done to determine the stack frame size is approximate
+and not conservative.
+The actual requirements may be somewhat greater than byte-size
+even if you do not get a warning. In addition, any space allocated
+via alloca
, variable-length arrays, or related constructs
+is not included by the compiler when determining
+whether or not to issue a warning.
+-Wframe-larger-than=‘PTRDIFF_MAX’ is enabled by default.
+Warnings controlled by the option can be disabled either by specifying
+byte-size of ‘SIZE_MAX’ or more or by
+-Wno-frame-larger-than.
+]]>
+
+
-Wfree-nonheap-object
Warn when attempting to free a non-heap object
- Warn when attempting to free a non-heap object.
-
- CRITICAL
-
-
- -Wfunction-elimination
- Warn about function call elimination
-
- Warn about function call elimination.
-
- CRITICAL
-
+ Warn when attempting to deallocate an object that was either not allocated
+on the heap, or by using a pointer that was not returned from a prior call
+to the corresponding allocation function. For example, because the call
+to stpcpy
returns a pointer to the terminating nul character and
+not to the beginning of the object, the call to free
below is
+diagnosed.
+
+
+
void f (char *p)
+{
+ p = stpcpy (p, "abc");
+ // ...
+ free (p); // warning
+}
+
+-Wfree-nonheap-object is included in -Wall.
+
]]>
+
+
+
+ -Wglobal-module
+ Warn about the global module fragment not containing only preprocessing directives
+
+ Disable the diagnostic for when the global module fragment of a module
+unit does not consist only of preprocessor directives.
+]]>
+
+
+
+ -Whardened
+ Warn when -fhardened did not enable an option from its set
+
+ Warn when -fhardened did not enable an option from its set (for
+which see -fhardened). For instance, using -fhardened
+and -fstack-protector at the same time on the command line causes
+-Whardened to warn because -fstack-protector-strong is
+not enabled by -fhardened.
+
+This warning is enabled by default and has effect only when -fhardened
+is enabled.
+
]]>
+
+
- -Whsa
- Issue a warning when HSAIL cannot be emitted for the compiled function or OpenMP construct.
+ -Wif-not-aligned
+ Warn when the field in a struct is not aligned
- Issue a warning when HSAIL cannot be emitted for the compiled function or OpenMP construct.
-
- CRITICAL
-
+ Control if warnings triggered by the warn_if_not_aligned
attribute
+should be issued. These warnings are enabled by default.
+]]>
+
+
-Wignored-attributes
- Warn when an attribute is ignored.
+ Warn whenever attributes are ignored
- Warn 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.
-
- CRITICAL
-
+ 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.
+]]>
+
+
-Wignored-qualifiers
- Warn whenever type qualifiers are ignored.
+ Warn whenever type qualifiers are ignored
+
+ Warn if the return type of a function has a type qualifier
+such as const
. For ISO C such a type qualifier has no effect,
+since the value returned by a function is not an lvalue.
+For C++, the warning is only emitted for scalar types or void
.
+ISO C prohibits qualified void
return types on function
+definitions, so such return types always receive a warning
+even without this option.
+
+This warning is also enabled by -Wextra.
+
]]>
+
+
+
+ -Wimplicit
+ Warn about implicit declarations
- Warn if the return type of a function has a type qualifier such as "const". For ISO
- C such a type qualifier has no effect, since the value returned by a function is not an lvalue.
- For C++, the warning is only emitted for scalar types or "void". ISO C prohibits qualified "void"
- return types on function definitions, so such return types always receive a warning even without
- this option.
-
- CRITICAL
-
+ Same as -Wimplicit-int and -Wimplicit-function-declaration.
+This warning is enabled by -Wall.
+]]>
+
+
-Wimplicit-fallthrough
Warn when a switch case falls through
- 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) {
+ 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) {
+ } else if (i < 1) {
bar (0);
- } else
+ } else
return;
- default:
- …
- }
-
- Since there are occasions where a switch case fall through is desirable, GCC provides
- an attribute, __attribute__ ((fallthrough)), that is to be used along with a null
- statement to suppress this warning that would normally occur:
-
- switch (cond)
- {
- case 1:
- bar (0);
- __attribute__ ((fallthrough));
- default:
- …
- }
-
- C++17 provides a standard way to suppress the -Wimplicit-fallthrough warning using
- [[fallthrough]]; instead of the GNU attribute. In C++11 or C++14 users can use
- [[gnu::fallthrough]];, which is a GNU extension. Instead of these attributes, it is
- also possible to add a fallthrough comment to silence the warning. The whole body
- of the C or C++ style comment should match the given regular expressions listed below.
- The option argument n specifies what kind of comments are accepted:
-
- -Wimplicit-fallthrough=0 disables the warning altogether.
- -Wimplicit-fallthrough=1 matches .* regular expression, any comment is used as fallthrough comment.
- -Wimplicit-fallthrough=2 case insensitively matches .*falls?[ \t-]*thr(ough|u).* regular expression.
- -Wimplicit-fallthrough=3 case sensitively matches one of the following regular expressions:
- -fallthrough
- @fallthrough@
- lint -fallthrough[ \t]*
- [ \t.!]*(ELSE,? |INTENTIONAL(LY)? )?
- FALL(S | |-)?THR(OUGH|U)[ \t.!]*(-[^\n\r]*)?
- [ \t.!]*(Else,? |Intentional(ly)? )?
- Fall((s | |-)[Tt]|t)hr(ough|u)[ \t.!]*(-[^\n\r]*)?
- [ \t.!]*([Ee]lse,? |[Ii]ntentional(ly)? )?
- fall(s | |-)?thr(ough|u)[ \t.!]*(-[^\n\r]*)?
- -Wimplicit-fallthrough=4 case sensitively matches one of the following regular expressions:
- -fallthrough
- @fallthrough@
- lint -fallthrough[ \t]*
- [ \t]*FALLTHR(OUGH|U)[ \t]*
- -Wimplicit-fallthrough=5 doesn’t recognize any comments as fallthrough comments, only attributes disable the warning.
-
- The comment needs to be followed after optional whitespace and other comments by case
- or default keywords or by a user label that precedes some case or default label.
-
- switch (cond)
- {
- case 1:
- bar (0);
- /* FALLTHRU */
- default:
- …
- }
-
- The -Wimplicit-fallthrough=3 warning is enabled by -Wextra.
-
- CRITICAL
-
+ default:
+ …
+ }
+
+Since there are occasions where a switch case fall through is desirable,
+GCC provides an attribute, __attribute__ ((fallthrough))
, that is
+to be used along with a null statement to suppress this warning that
+would normally occur:
+
+
+
switch (cond)
+ {
+ case 1:
+ bar (0);
+ __attribute__ ((fallthrough));
+ default:
+ …
+ }
+
+C++17 provides a standard way to suppress the -Wimplicit-fallthrough
+warning using [[fallthrough]];
instead of the GNU attribute. In C++11
+or C++14 users can use [[gnu::fallthrough]];
, which is a GNU extension.
+Instead of these attributes, it is also possible to add a fallthrough comment
+to silence the warning. The whole body of the C or C++ style comment should
+match the given regular expressions listed below. The option argument n
+specifies what kind of comments are accepted:
+
+
+- -Wimplicit-fallthrough=0 disables the warning altogether.
+
+
- -Wimplicit-fallthrough=1 matches
.*
regular
+expression, any comment is used as fallthrough comment.
+
+ - -Wimplicit-fallthrough=2 case insensitively matches
+
.*falls?[ \t-]*thr(ough|u).*
regular expression.
+
+ - -Wimplicit-fallthrough=3 case sensitively matches one of the
+following regular expressions:
+
+
+-fallthrough
+@fallthrough@
+lint -fallthrough[ \t]*
+[ \t.!]*(ELSE,? |INTENTIONAL(LY)? )?
FALL(S | |-)?THR(OUGH|U)[ \t.!]*(-[^\n\r]*)?
+[ \t.!]*(Else,? |Intentional(ly)? )?
Fall((s | |-)[Tt]|t)hr(ough|u)[ \t.!]*(-[^\n\r]*)?
+[ \t.!]*([Ee]lse,? |[Ii]ntentional(ly)? )?
fall(s | |-)?thr(ough|u)[ \t.!]*(-[^\n\r]*)?
+
+ - -Wimplicit-fallthrough=4 case sensitively matches one of the
+following regular expressions:
+
+
+-fallthrough
+@fallthrough@
+lint -fallthrough[ \t]*
+[ \t]*FALLTHR(OUGH|U)[ \t]*
+
+ - -Wimplicit-fallthrough=5 doesn’t recognize any comments as
+fallthrough comments, only attributes disable the warning.
+
+
+The comment needs to be followed after optional whitespace and other comments
+by case
or default
keywords or by a user label that precedes some
+case
or default
label.
+
+
+
switch (cond)
+ {
+ case 1:
+ bar (0);
+ /* FALLTHRU */
+ default:
+ …
+ }
+
+The -Wimplicit-fallthrough=3 warning is enabled by -Wextra.
+
]]>
+
+
-Wimplicit-function-declaration
Warn about implicit function declarations
- Give a warning whenever a function is used before being declared.
-
- CRITICAL
-
+ 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-int
Warn when a declaration does not specify a type
- Warn when a declaration does not specify a type.
-
- CRITICAL
-
-
- -Wimplicit-interface
- Warn about calls with implicit interface
-
- Warn about calls with implicit interface.
-
- CRITICAL
-
-
- -Wimplicit-procedure
- Warn about called procedures not explicitly declared
-
- Warn about called procedures not explicitly declared.
-
- CRITICAL
-
+ 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.
+
]]>
+
+
+
+ -Winaccessible-base
+ Warn when a base is inaccessible in derived due to ambiguity
+
+ This option controls warnings
+when a base class is inaccessible in a class derived from it due to
+ambiguity. The warning is enabled by default.
+Note that the warning for ambiguous virtual
+bases is enabled by the -Wextra option.
+
+
struct A { int a; };
+
+struct B : A { };
+
+struct C : B, A { };
+
]]>
+
+
+
+ -Wincompatible-pointer-types
+ Warn when there is a conversion between pointers that have incompatible types
+
+ Warn when there is a conversion between pointers that have incompatible
+types. This warning is for cases not covered by -Wno-pointer-sign,
+which warns for pointer argument passing or assignment with different
+signedness.
+
+By default, in C99 and later dialects of C, GCC treats this issue as an
+error. The error can be downgraded to a warning using
+-fpermissive (along with certain other errors), or for this
+error alone, with -Wno-error=incompatible-pointer-types.
+
+This warning is upgraded to an error by -pedantic-errors.
+
]]>
+
+
+
+ -Winfinite-recursion
+ Warn for infinitely recursive calls
+
+ Warn about infinitely recursive calls. The warning is effective at all
+optimization levels but requires optimization in order to detect infinite
+recursion in calls between two or more functions.
+-Winfinite-recursion is included in -Wall.
+
+Compare with -Wanalyzer-infinite-recursion which provides a
+similar diagnostic, but is implemented in a different way (as part of
+-fanalyzer).
+
]]>
+
+
+
+ -Winherited-variadic-ctor
+ Warn about C++11 inheriting constructors when the base has a variadic constructor
+
+ 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.
+]]>
+
+
+
+ -Winit-list-lifetime
+ Warn about uses of std::initializer_list that can result in dangling pointers
+
+ Warn about uses of std::initializer_list
that are likely
+to result in dangling pointers. Since the underlying array for an
+initializer_list
is handled like a normal C++ temporary object,
+it is easy to inadvertently keep a pointer to the array past the end
+of the array’s lifetime. For example:
+
+
+- If a function returns a temporary
initializer_list
, or a local
+initializer_list
variable, the array’s lifetime ends at the end
+of the return statement, so the value returned has a dangling pointer.
+
+ - If a new-expression creates an
initializer_list
, the array only
+lives until the end of the enclosing full-expression, so the
+initializer_list
in the heap has a dangling pointer.
+
+ - When an
initializer_list
variable is assigned from a
+brace-enclosed initializer list, the temporary array created for the
+right side of the assignment only lives until the end of the
+full-expression, so at the next statement the initializer_list
+variable has a dangling pointer.
+
+
+
// li's initial underlying array lives as long as li
+std::initializer_list<int> li = { 1,2,3 };
+// assignment changes li to point to a temporary array
+li = { 4, 5 };
+// now the temporary is gone and li has a dangling pointer
+int i = li.begin()[0] // undefined behavior
+
+ - When a list constructor stores the
begin
pointer from the
+initializer_list
argument, this doesn’t extend the lifetime of
+the array, so if a class variable is constructed from a temporary
+initializer_list
, the pointer is left dangling by the end of
+the variable declaration statement.
+
+
]]>
+
+
-Winit-self
Warn about variables which are initialized to themselves
- Warn about uninitialized variables which are initialized with themselves.
-
- For example, GCC will warn about "i" being uninitialized in the following snippet only when
- -Winit-self has been specified:
-
- int f()
- {
- int i = i;
- return i;
- }
-
- CRITICAL
-
+ 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++.
+
]]>
+
+
-Winline
Warn when an inlined function cannot be inlined
- Warn if a function can not be inlined and it was declared as inline. Even with this
- option, the compiler will not warn about failures to inline functions declared in system headers.
-
- The compiler uses a variety of heuristics to determine whether or not to inline a function. For
- example, the compiler takes into account the size of the function being inlined and the amount of
- inlining that has already been done in the current function. Therefore, seemingly insignificant
- changes in the source program can cause the warnings produced by -Winline to appear or disappear.
-
- CRITICAL
-
+ Warn if a function that is declared as inline cannot be inlined.
+Even with this option, the compiler does not warn about failures to
+inline functions declared in system headers.
+
+The compiler uses a variety of heuristics to determine whether or not
+to inline a function. For example, the compiler takes into account
+the size of the function being inlined and the amount of inlining
+that has already been done in the current function. Therefore,
+seemingly insignificant changes in the source program can cause the
+warnings produced by -Winline to appear or disappear.
+
]]>
+
+
+
+ -Wint-conversion
+ Warn about incompatible integer to pointer and pointer to integer conversions
+
+ Warn about incompatible integer to pointer and pointer to integer
+conversions. This warning is about implicit conversions; for explicit
+conversions the warnings -Wno-int-to-pointer-cast and
+-Wno-pointer-to-int-cast may be used.
+
+By default, in C99 and later dialects of C, GCC treats this issue as an
+error. The error can be downgraded to a warning using
+-fpermissive (along with certain other errors), or for this
+error alone, with -Wno-error=int-conversion.
+
+This warning is upgraded to an error by -pedantic-errors.
+
]]>
+
+
-Wint-in-bool-context
- Warn for suspicious use of integer values where boolean values are expected
-
- Warn for suspicious use of integer values where boolean values are expected, such as
- conditional expressions (?:) using non-boolean integer constants in boolean context,
- like if (a <= b ? 2 : 3). Or left shifting of signed integers in boolean context,
- like for (a = 0; 1 << a; a++);. Likewise for all kinds of multiplications
- regardless of the data type. This warning is enabled by -Wall.
-
- CRITICAL
-
+ Warn for suspicious integer expressions in boolean context
+
+ Warn for suspicious use of integer values where boolean values are expected,
+such as conditional expressions (?:) using non-boolean integer constants in
+boolean context, like if (a <= b ? 2 : 3)
. Or left shifting of signed
+integers in boolean context, like for (a = 0; 1 << a; a++);
. Likewise
+for all kinds of multiplications regardless of the data type.
+This warning is enabled by -Wall.
+]]>
+
+
-Wint-to-pointer-cast
Warn when there is a cast to a pointer from an integer of a different size
- Warn when casting to pointer type of an integer of a different size. In C++, casting
- to a pointer type of smaller size is an error.
-
- CRITICAL
-
+ Suppress warnings from casts to pointer type of an integer of a
+different size. In C++, casting to a pointer type of smaller size is
+an error. Wint-to-pointer-cast is enabled by default.
+]]>
+
+
- -Wintrinsic-shadow
- Warn if a user-procedure has the same name as an intrinsic
+ -Winterference-size
+ Warn about nonsensical values of --param destructive-interference-size or constructive-interference-size
- Warn if a user-procedure has the same name as an intrinsic.
-
- CRITICAL
-
+ Warn about use of C++17 std::hardware_destructive_interference_size
+without specifying its value with --param destructive-interference-size.
+Also warn about questionable values for that option.
+
+This variable is intended to be used for controlling class layout, to
+avoid false sharing in concurrent code:
+
+
+
struct independent_fields {
+ alignas(std::hardware_destructive_interference_size)
+ std::atomic<int> one;
+ alignas(std::hardware_destructive_interference_size)
+ std::atomic<int> two;
+};
+
+Here ‘one’ and ‘two’ are intended to be far enough apart
+that stores to one won’t require accesses to the other to reload the
+cache line.
+
+By default, --param destructive-interference-size and
+--param constructive-interference-size are set based on the
+current -mtune option, typically to the L1 cache line size
+for the particular target CPU, sometimes to a range if tuning for a
+generic target. So all translation units that depend on ABI
+compatibility for the use of these variables must be compiled with
+the same -mtune (or -mcpu).
+
+If ABI stability is important, such as if the use is in a header for a
+library, you should probably not use the hardware interference size
+variables at all. Alternatively, you can force a particular value
+with --param.
+
+If you are confident that your use of the variable does not affect ABI
+outside a single build of your project, you can turn off the warning
+with -Wno-interference-size.
+
]]>
+
+
- -Wintrinsics-std
- Warn on intrinsics not part of the selected standard
+ -Winvalid-constexpr
+ Warn when a function never produces a constant expression
- Warn on intrinsics not part of the selected standard.
-
- CRITICAL
-
+ Warn when a function never produces a constant expression. In C++20
+and earlier, for every constexpr
function and function template,
+there must be at least one set of function arguments in at least one
+instantiation such that an invocation of the function or constructor
+could be an evaluated subexpression of a core constant expression.
+C++23 removed this restriction, so it’s possible to have a function
+or a function template marked constexpr
for which no invocation
+satisfies the requirements of a core constant expression.
+
+This warning is enabled as a pedantic warning by default in C++20 and
+earlier. In C++23, -Winvalid-constexpr can be turned on, in
+which case it will be an ordinary warning. For example:
+
+
+
void f (int& i);
+constexpr void
+g (int& i)
+{
+ // Warns by default in C++20, in C++23 only with -Winvalid-constexpr.
+ f(i);
+}
+
]]>
+
+
+
+ -Winvalid-imported-macros
+ Warn about macros that have conflicting header units definitions
+
+ 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.
+]]>
+
+
-Winvalid-memory-model
- Warn when an atomic memory model parameter is known to be outside the valid range.
-
- Warn when an atomic memory model parameter is known to be outside the valid range.
-
- CRITICAL
-
+ Warn when an atomic memory model parameter is known to be outside the valid range
+
+ This option controls warnings
+for invocations of Built-in Functions for Memory Model Aware Atomic Operations, Legacy __sync
Built-in Functions for Atomic Memory Access,
+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.
+
]]>
+
+
-Winvalid-offsetof
Warn about invalid uses of the "offsetof" macro
- Warn when applying the offsetof macro to a non-POD type. According to the 1998 ISO
- C++ standard, applying offsetof to a non-POD type is undefined. In existing C++ implementations,
- however, offsetof typically gives meaningful results even when applied to certain kinds of non-POD
- types. (Such as a simple struct that fails to be a POD type only by virtue of having a constructor.)
-
- The restrictions on offsetof may be relaxed in a future version of the C++ standard.
-
-
- CRITICAL
-
+ 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.
+
]]>
+
+
-Winvalid-pch
Warn about PCH files that are found but not used
- Warn if a precompiled header is found in the search path but can't be used.
-
- CRITICAL
-
+ Warn if a precompiled header (see Using Precompiled Headers) is found in
+the search path but cannot be used.
+]]>
+
+
+
+ -Winvalid-utf8
+ Warn about invalid UTF-8 characters
+
+ Warn if an invalid UTF-8 character is found.
+This warning is on by default for C++23 if -finput-charset=UTF-8
+is used and turned into error with -pedantic-errors.
+]]>
+
+
-Wjump-misses-init
Warn when a jump misses a variable initialization
- 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 which 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.
-
- CRITICAL
-
+ 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.
+
]]>
+
+
-Wlarger-than
- Warn if an object is larger than specified number of bytes
+ Warn if an object's size exceeds <byte-size>
- Warn whenever an object larger than the specified length (in bytes) is defined.
-
- CRITICAL
-
-
- -Wline-truncation
- Warn about truncated source lines
-
- Warn about truncated source lines.
-
- CRITICAL
-
+ Warn whenever an object is defined whose size exceeds byte-size.
+-Wlarger-than=‘PTRDIFF_MAX’ is enabled by default.
+Warnings controlled by the option can be disabled either by specifying
+byte-size of ‘SIZE_MAX’ or more or by -Wno-larger-than.
+
+Also warn for calls to bounded functions such as memchr
or
+strnlen
that specify a bound greater than the largest possible
+object, which is ‘PTRDIFF_MAX’ bytes by default. These warnings
+can only be disabled by -Wno-larger-than.
+
]]>
+
+
-Wliteral-suffix
Warn when a string or character literal is followed by a ud-suffix which does not begin with an underscore
-
- 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.
-
- Additionally, warn when a user-defined literal operator is declared with a
- literal suffix identifier that doesn’t begin with an underscore. Literal
- suffix identifiers that don’t begin with an underscore are reserved for
- future standardization.
- ]]>
-
- CRITICAL
-
+
+ Warn when a string or character literal is followed by a
+ud-suffix which does not begin with an underscore. As a conforming
+extension, GCC treats such suffixes as separate preprocessing tokens
+in order to maintain backwards compatibility with code that uses
+formatting macros from <inttypes.h>
. For example:
+
+
+
#define __STDC_FORMAT_MACROS
+#include <inttypes.h>
+#include <stdio.h>
+
+int main() {
+ int64_t i64 = 123;
+ printf("My int64: %" PRId64"\n", i64);
+}
+
+In this case, PRId64
is treated as a separate preprocessing token.
+
+This option also controls warnings when a user-defined literal
+operator is declared with a literal suffix identifier that doesn’t
+begin with an underscore. Literal suffix identifiers that don’t begin
+with an underscore are reserved for future standardization.
+
+These warnings are enabled by default.
+
]]>
+
+
-Wlogical-not-parentheses
- Warn about logical not used on the left hand side operand of a comparison
-
- Warn about logical not used on the left hand side operand of a comparison.
- This option does not warn if the RHS operand is of a boolean type. 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.
-
- CRITICAL
-
+ Warn when logical not is used on the left hand side operand of a comparison
+
+ 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:
+
+This warning is enabled by -Wall.
+
]]>
+
+
-Wlogical-op
Warn when a logical operator is suspiciously always evaluating to true or false
- 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.
-
- CRITICAL
-
+ 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) { … }
+
]]>
+
+
-Wlong-long
- Warn if long long type is used.
+ Warn about using "long long"
- Warn if long long type is used.
-
- CRITICAL
-
+ Warn if long long
type is used. This is enabled by either
+-Wpedantic or -Wtraditional in ISO C90 and C++98
+modes. To inhibit the warning messages, use -Wno-long-long.
+
+This warning is upgraded to an error by -pedantic-errors.
+
]]>
+
+
-Wlto-type-mismatch
- During the link-time optimization warn about type mismatches in global declarations from different compilation units
+ During link time optimization warn about mismatched types of global declarations
- During the link-time optimization warn about type mismatches in global declarations
- from different compilation units. Requires -flto to be enabled.
-
- CRITICAL
-
+ During the link-time optimization, do not warn about type mismatches in
+global declarations from different compilation units.
+Requires -flto to be enabled. Enabled by default.
+]]>
+
+
-Wmain
Warn about suspicious declarations of "main"
- 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.
-
- CRITICAL
-
+ 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.
+
]]>
+
+
-Wmaybe-uninitialized
Warn about maybe uninitialized automatic variables
- Warn about maybe uninitialized automatic variables
-
- CRITICAL
-
+ For an object with automatic or allocated storage duration, if there exists
+a path from the function entry to a use of the object that is initialized,
+but there exist some other paths for which the object is not initialized,
+the compiler emits a warning if it cannot prove the uninitialized paths
+are not executed at run time.
+
+In addition, passing a pointer (or in C++, a reference) to an uninitialized
+object to a const
-qualified function argument is also diagnosed by
+this warning. (-Wuninitialized is issued for built-in functions
+known to read the object.) Annotating the function with attribute
+access (none)
indicates that the argument isn’t used to access
+the object and avoids the warning (see Common Function Attributes).
+
+These warnings are only possible in optimizing compilation, because otherwise
+GCC does not keep track of the state of variables.
+
+These warnings are made optional because GCC may not be able to determine when
+the code is correct in spite of appearing to have an error. Here is one
+example of how this can happen:
+
+
+
{
+ int x;
+ switch (y)
+ {
+ case 1: x = 1;
+ break;
+ case 2: x = 4;
+ break;
+ case 3: x = 5;
+ }
+ foo (x);
+}
+
+If the value of y
is always 1, 2 or 3, then x
is
+always initialized, but GCC doesn’t know this. To suppress the
+warning, you need to provide a default case with assert(0) or
+similar code.
+
+
+This option also warns when a non-volatile automatic variable might be
+changed by a call to longjmp
.
+The compiler sees only the calls to setjmp
. It cannot know
+where longjmp
will be called; in fact, a signal handler could
+call it at any point in the code. As a result, you may get a warning
+even when there is in fact no problem because longjmp
cannot
+in fact be called at the place that would cause a problem.
+
+Some spurious warnings can be avoided if you declare all the functions
+you use that never return as noreturn
. See Declaring Attributes of Functions.
+
+This warning is enabled by -Wall or -Wextra.
+
]]>
+
+
-Wmemset-elt-size
- Warn for suspicious calls to the memset built-in function
+ Warn about suspicious calls to memset where the third argument contains the number of elements not multiplied by the element 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.
-
- CRITICAL
-
+ 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.
+]]>
+
+
-Wmemset-transposed-args
- Warn for suspicious calls to the memset built-in function
-
- Warn for suspicious calls to the memset built-in function, if the second argument
- is not zero and the third argument is zero. This warns e.g. about
- memset (buf, sizeof buf, 0) where most probably memset (buf, 0, sizeof buf) was
- meant instead. The diagnostics is only emitted if the third argument is literal
- zero. If it is some expression that is folded to zero, a cast of zero to some
- type, etc., it is far less likely that the user has mistakenly exchanged the
- arguments and no warning is emitted. This warning is enabled by -Wall.
-
- CRITICAL
-
+ Warn about suspicious calls to memset where the third argument is constant literal zero and the second is not
+
+ 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.
+]]>
+
+
-Wmisleading-indentation
Warn when the indentation of the code does not reflect the block structure
- Warn when the indentation of the code does not reflect the block structure. Specifically,
- a warning is issued for if, else, while, and for clauses with a guarded statement that
- does not use braces, followed by an unguarded statement with the same indentation.
-
- In the following example, the call to “bar” is misleadingly indented as if it were guarded
- by the “if” conditional.
-
- if (some_condition ())
- foo ();
- bar (); /* Gotcha: this is not guarded by the "if". */
-
- In the case of mixed tabs and spaces, the warning uses the -ftabstop= option to determine
- if the statements line up (defaulting to 8).
-
- The warning is not issued for code involving multiline preprocessor logic such as the
- following example.
-
- if (flagA)
- foo (0);
- #if SOME_CONDITION_THAT_DOES_NOT_HOLD
- if (flagB)
- #endif
- foo (1);
-
- The warning is not issued after a #line directive, since this typically indicates
- autogenerated code, and no assumptions can be made about the layout of the file that the
- directive references.
-
- This warning is enabled by -Wall in C and C++.
-
- CRITICAL
-
+ Warn when the indentation of the code does not reflect the block structure.
+Specifically, a warning is issued for if
, else
, while
, and
+for
clauses with a guarded statement that does not use braces,
+followed by an unguarded statement with the same indentation.
+
+In the following example, the call to “bar” is misleadingly indented as
+if it were guarded by the “if” conditional.
+
+
+
if (some_condition ())
+ foo ();
+ bar (); /* Gotcha: this is not guarded by the "if". */
+
+In the case of mixed tabs and spaces, the warning uses the
+-ftabstop= option to determine if the statements line up
+(defaulting to 8).
+
+The warning is not issued for code involving multiline preprocessor logic
+such as the following example.
+
+
+
if (flagA)
+ foo (0);
+#if SOME_CONDITION_THAT_DOES_NOT_HOLD
+ if (flagB)
+#endif
+ foo (1);
+
+The warning is not issued after a #line
directive, since this
+typically indicates autogenerated code, and no assumptions can be made
+about the layout of the file that the directive references.
+
+This warning is enabled by -Wall in C and C++.
+
]]>
+
+
+
+ -Wmismatched-dealloc
+ Warn for deallocation calls with arguments returned from mismatched allocation functions
+
+ Warn for calls to deallocation functions with pointer arguments returned
+from allocation functions for which the former isn’t a suitable
+deallocator. A pair of functions can be associated as matching allocators
+and deallocators by use of attribute malloc
. Unless disabled by
+the -fno-builtin option the standard functions calloc
,
+malloc
, realloc
, and free
, as well as the corresponding
+forms of C++ operator new
and operator delete
are implicitly
+associated as matching allocators and deallocators. In the following
+example mydealloc
is the deallocator for pointers returned from
+myalloc
.
+
+
+
void mydealloc (void*);
+
+__attribute__ ((malloc (mydealloc, 1))) void*
+myalloc (size_t);
+
+void f (void)
+{
+ void *p = myalloc (32);
+ // …use p…
+ free (p); // warning: not a matching deallocator for myalloc
+ mydealloc (p); // ok
+}
+
+In C++, the related option -Wmismatched-new-delete diagnoses
+mismatches involving either operator new
or operator delete
.
+
+Option -Wmismatched-dealloc is included in -Wall.
+
]]>
+
+
+
+ -Wmismatched-new-delete
+ Warn for mismatches between calls to operator new or delete and the corresponding call to the allocation or deallocation function
+
+ Warn for mismatches between calls to operator new
or operator
+delete
and the corresponding call to the allocation or deallocation function.
+This includes invocations of C++ operator delete
with pointers
+returned from either mismatched forms of operator new
, or from other
+functions that allocate objects for which the operator delete
isn’t
+a suitable deallocator, as well as calls to other deallocation functions
+with pointers returned from operator new
for which the deallocation
+function isn’t suitable.
+
+For example, the delete
expression in the function below is diagnosed
+because it doesn’t match the array form of the new
expression
+the pointer argument was returned from. Similarly, the call to free
+is also diagnosed.
+
+
+
void f ()
+{
+ int *a = new int[n];
+ delete a; // warning: mismatch in array forms of expressions
+
+ char *p = new char[n];
+ free (p); // warning: mismatch between new and free
+}
+
+The related option -Wmismatched-dealloc diagnoses mismatches
+involving allocation and deallocation functions other than operator
+new
and operator delete
.
+
+-Wmismatched-new-delete is included in -Wall.
+
]]>
+
+
+
+ -Wmismatched-tags
+ Warn when a class is redeclared or referenced using a mismatched class-key
+
+ Warn for declarations of structs, classes, and class templates and their
+specializations with a class-key that does not match either the definition
+or the first declaration if no definition is provided.
+
+For example, the declaration of struct Object
in the argument list
+of draw
triggers the warning. To avoid it, either remove the redundant
+class-key struct
or replace it with class
to match its definition.
+
+
class Object {
+public:
+ virtual ~Object () = 0;
+};
+void draw (struct Object*);
+
+It is not wrong to declare a class with the class-key struct
as
+the example above shows. The -Wmismatched-tags option is intended
+to help achieve a consistent style of class declarations. In code that is
+intended to be portable to Windows-based compilers the warning helps prevent
+unresolved references due to the difference in the mangling of symbols
+declared with different class-keys. The option can be used either on its
+own or in conjunction with -Wredundant-tags.
+
]]>
+
+
+
+ -Wmissing-attributes
+ Warn about declarations of entities that may be missing attributes that related entities have been declared with
+
+ Warn when a declaration of a function is missing one or more attributes
+that a related function is declared with and whose absence may adversely
+affect the correctness or efficiency of generated code. For example,
+the warning is issued for declarations of aliases that use attributes
+to specify less restrictive requirements than those of their targets.
+This typically represents a potential optimization opportunity.
+By contrast, the -Wattribute-alias=2 option controls warnings
+issued when the alias is more restrictive than the target, which could
+lead to incorrect code generation.
+Attributes considered include alloc_align
, alloc_size
,
+cold
, const
, hot
, leaf
, malloc
,
+nonnull
, noreturn
, nothrow
, pure
,
+returns_nonnull
, and returns_twice
.
+
+In C++, the warning is issued when an explicit specialization of a primary
+template declared with attribute alloc_align
, alloc_size
,
+assume_aligned
, format
, format_arg
, malloc
,
+or nonnull
is declared without it. Attributes deprecated
,
+error
, and warning
suppress the warning.
+(see Declaring Attributes of Functions).
+
+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 Common Function Attributes),
+variables (see Common Variable Attributes), or types
+(see Common Type Attributes).
+
+-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 about possibly missing braces around initializers
- 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 } };
-
- CRITICAL
-
+ 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-declarations
Warn about global functions without previous declarations
- Warn if a global function is defined without a previous declaration. Do so even if
- the definition itself provides a prototype. Use this option to detect global functions that are
- not declared in header files. In C++, no warnings are issued for function templates, or for inline
- functions, or for functions in anonymous namespaces.
-
- CRITICAL
-
+ Warn if a global function is defined without a previous declaration.
+Do so even if the definition itself provides a prototype.
+Use this option to detect global functions that are not declared in
+header files. In C, no warnings are issued for functions with previous
+non-prototype declarations; use -Wmissing-prototypes to detect
+missing prototypes. In C++, no warnings are issued for function templates,
+or for inline functions, or for functions in anonymous namespaces.
+]]>
+
+
-Wmissing-field-initializers
Warn about missing fields in struct initializers
- Warn if a structure's initializer has some fields missing. For example, the following
- code would cause such a warning, because "x.h" is implicitly zero:
-
- struct s { int f, g, h; };
- struct s x = { 3, 4 };
-
- This option does not warn about designated initializers, so the following modification would not
- trigger a warning:
-
- struct s { int f, g, h; };
- struct s x = { .f = 3, .g = 4 };
-
- CRITICAL
-
-
- -Wmissing-format-attribute
- Warn about functions which might be candidates for format attributes
-
- Warn about function pointers that might be candidates for "format" attributes. Note
- these are only possible candidates, not absolute ones. GCC will guess that function pointers with
- "format" attributes that are used in assignment, initialization, parameter passing or return
- statements should have a corresponding "format" attribute in the resulting type. I.e. the left-hand
- side of the assignment or initialization, the type of the parameter variable, or the return type
- of the containing function respectively should also have a "format" attribute to avoid the warning.
-
- GCC will also warn about function definitions that might be candidates for "format" attributes.
- Again, these are only possible candidates. GCC will guess that "format" attributes might be
- appropriate for any function that calls a function like "vprintf" or "vscanf", but this might not
- always be the case, and some functions for which "format" attributes are appropriate may not be
- detected.
-
- CRITICAL
-
+ Warn if a structure’s initializer has some fields missing. For
+example, the following code causes such a warning, because
+x.h
is implicitly zero:
+
+
+
struct s { int f, g, h; };
+struct s x = { 3, 4 };
+
+In C this option does not warn about designated initializers, so the
+following modification does not trigger a warning:
+
+
+
struct s { int f, g, h; };
+struct s x = { .f = 3, .g = 4 };
+
+In C this option does not warn about the universal zero initializer
+‘{ 0 }’:
+
+
+
struct s { int f, g, h; };
+struct s x = { 0 };
+
+Likewise, in C++ this option does not warn about the empty { }
+initializer, for example:
+
+
+
struct s { int f, g, h; };
+s x = { };
+
+This warning is included in -Wextra. To get other -Wextra
+warnings without this one, use -Wextra -Wno-missing-field-initializers.
+
]]>
+
+
-Wmissing-include-dirs
Warn about user-specified include directories that do not exist
- Warn if a user-supplied include directory does not exist.
-
- CRITICAL
-
-
- -Wmissing-noreturn
- Warn about functions which might be candidates for __attribute__((noreturn))
-
- Warn about functions which might be candidates for __attribute__((noreturn))
-
- CRITICAL
-
+ Warn if a user-supplied include directory does not exist. This option is disabled
+by default for C, C++, Objective-C and Objective-C++. For Fortran, it is partially
+enabled by default by warning for -I and -J, only.
+]]>
+
+
-Wmissing-parameter-type
Warn about function parameters declared without a type specifier in K&R-style functions
-
- void foo(bar) { }
-
-]]>
-
- CRITICAL
-
+
+ A function parameter is declared without a type specifier in K&R-style
+functions:
+
+
+This warning is also enabled by -Wextra.
+
]]>
+
+
+
+ -Wmissing-profile
+ Warn in case profiles in -fprofile-use do not exist
+
+ This option controls warnings if feedback profiles are missing when using the
+-fprofile-use option.
+This option diagnoses those cases where a new function or a new file is added
+between compiling with -fprofile-generate and with
+-fprofile-use, without regenerating the profiles.
+In these cases, the profile feedback data files do not contain any
+profile feedback information for
+the newly added function or file respectively. Also, in the case when profile
+count data (.gcda) files are removed, GCC cannot use any profile feedback
+information. In all these cases, warnings are issued to inform you that a
+profile generation step is due.
+Ignoring the warning can result in poorly optimized code.
+-Wno-missing-profile can be used to
+disable the warning, but this is not recommended and should be done only
+when non-existent profile data is justified.
+]]>
+
+
-Wmissing-prototypes
Warn about global functions without prototypes
- Warn if a global function is defined without a previous prototype declaration. This
- warning is issued even if the definition itself provides a prototype. The aim is to detect global
- functions that are not declared in header files.
-
- CRITICAL
-
+ Warn if a global function is defined without a previous prototype
+declaration. This warning is issued even if the definition itself
+provides a prototype. Use this option to detect global functions
+that do not have a matching prototype declaration in a header file.
+This option is not valid for C++ because all function declarations
+provide prototypes and a non-matching declaration declares an
+overload rather than conflict with an earlier declaration.
+Use -Wmissing-declarations to detect missing declarations in C++.
+]]>
+
+
+
+ -Wmissing-requires
+ Warn about likely missing requires keyword
+
+ By default, the compiler warns about a concept-id appearing as a C++20 simple-requirement:
+
+
+
bool satisfied = requires { C<T> };
+
+Here ‘satisfied’ will be true if ‘C<T>’ is a valid
+expression, which it is for all T. Presumably the user meant to write
+
+
+
bool satisfied = requires { requires C<T> };
+
+so ‘satisfied’ is only true if concept ‘C’ is satisfied for
+type ‘T’.
+
+This warning can be disabled with -Wno-missing-requires.
+
]]>
+
+
- -Wmudflap
- Warn about constructs not instrumented by -fmudflap
+ -Wmissing-template-keyword
+ Warn when the template keyword is missing after a member access token in a dependent member access expression if that member is a template
- Warn about constructs that cannot be instrumented by -fmudflap.
-
- CRITICAL
-
+ The member access tokens ., -> and :: must be followed by the template
+keyword if the parent object is dependent and the member being named is a
+template.
+
+
+
template <class X>
+void DoStuff (X x)
+{
+ x.template DoSomeOtherStuff<X>(); // Good.
+ x.DoMoreStuff<X>(); // Warning, x is dependent.
+}
+
+In rare cases it is possible to get false positives. To silence this, wrap
+the expression in parentheses. For example, the following is treated as a
+template, even where m and N are integers:
+
+
+
void NotATemplate (my_class t)
+{
+ int N = 5;
+
+ bool test = t.m < N > (0); // Treated as a template.
+ test = (t.m < N) > (0); // Same meaning, but not treated as a template.
+}
+
+This warning can be disabled with -Wno-missing-template-keyword.
+
]]>
+
+
+
+ -Wmissing-variable-declarations
+ Warn about global variables without previous declarations
+
+ Warn if a global variable is defined without a previous declaration.
+Use this option to detect global variables that do not have a matching
+extern declaration in a header file.
+]]>
+
+
-Wmultichar
Warn about use of multi-character character constants
- Warn if a multicharacter constant ('FOOF') is used. Usually they indicate a typo in
- the user's code, as they have implementation-defined values, and should not be used in portable
- code.
-
- CRITICAL
-
+ Warn if a multicharacter constant (‘'FOOF'’) is used.
+Usually they indicate a typo in the user’s code, as they have
+implementation-defined values, and should not be used in portable code.
+]]>
+
+
-Wmultiple-inheritance
- Warn when a class is defined with multiple direct base classes
+ Warn on direct multiple inheritance
- Warn when a class is defined with multiple direct base classes. Some coding rules disallow
- multiple inheritance, and this may be used to enforce that rule. The warning is inactive inside
- a system header file, such as the STL, so one can still use the STL. One may also define
- classes that indirectly use multiple inheritance.
-
- CRITICAL
-
+ Warn when a class is defined with multiple direct base classes. Some
+coding rules disallow multiple inheritance, and this may be used to
+enforce that rule. The warning is inactive inside a system header file,
+such as the STL, so one can still use the STL. One may also define
+classes that indirectly use multiple inheritance.
+]]>
+
+
-Wmultistatement-macros
- Warn about unsafe multiple statement macros that appear to be guarded by a clause
+ Warn about unsafe macros expanding to multiple statements used as a body of a clause such as if, else, while, switch, or for
- 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++.
-
- CRITICAL
-
+ 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++.
+
]]>
+
+
- -Wnarrowing
- Warn about narrowing conversions within { } that are ill-formed in C++11
+ -Wnamespaces
+ Warn on namespace definition
- Warn when a narrowing conversion prohibited by C++11 occurs within { }, e.g.
-
- int i = { 2.2 }; // error: narrowing from double to int
-
- This flag is included in -Wall and -Wc++11-compat.
-
- With -std=c++11, -Wno-narrowing suppresses the diagnostic required by the standard. Note that this
- does not affect the meaning of well-formed code; narrowing conversions are still considered ill-formed
- in SFINAE context.
-
- CRITICAL
-
+ Warn when a namespace definition is opened. Some coding rules disallow
+namespaces, and this may be used to enforce that rule. The warning is
+inactive inside a system header file, such as the STL, so one can still
+use the STL. One may also use using directives and qualified names.
+]]>
+
+
- -Wnamespaces
- Warn when a namespace definition is opened
+ -Wnarrowing
+ Warn about narrowing conversions within { } that are ill-formed in C++11
- Warn when a namespace definition is opened. Some coding rules disallow namespaces, and this may be
- used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so
- one can still use the STL. One may also use using directives and qualified names.
-
- CRITICAL
-
+ For C++11 and later standards, narrowing conversions are diagnosed by default,
+as required by the standard. A narrowing conversion from a constant produces
+an error, and a narrowing conversion from a non-constant produces a warning,
+but -Wno-narrowing suppresses the diagnostic.
+Note that this does not affect the meaning of well-formed code;
+narrowing conversions are still considered ill-formed in SFINAE contexts.
+
+With -Wnarrowing in C++98, warn when a narrowing
+conversion prohibited by C++11 occurs within
+‘{ }’, e.g.
+
+
+
int i = { 2.2 }; // error: narrowing from double to int
+
+This flag is included in -Wall and -Wc++11-compat.
+
]]>
+
+
-Wnested-externs
Warn about "extern" declarations not at file scope
- Warn if an "extern" declaration is encountered within a function.
-
- CRITICAL
-
-
- -Wno-aggressive-loop-optimizations
- Warn if in a loop with constant number of iterations the compiler detects undefined behavior in some statement during one or more of the iterations.
-
- Warn if in a loop with constant number of iterations the compiler detects undefined behavior in
- some statement during one or more of the iterations.
-
- CRITICAL
-
-
- -Wno-builtin-declaration-mismatch
- Warn if a built-in function is declared with the wrong signature
-
- Warn if a built-in function is declared with the wrong signature. This warning is enabled by default.
-
- CRITICAL
-
+ Warn if an extern
declaration is encountered within a function.
+]]>
+
+
-Wnoexcept
Warn when a noexcept expression evaluates to false even though the expression can't actually throw
- Warn when a noexcept-expression evaluates to false because of a call to a function
- that does not have a non-throwing exception specification (i.e. throw() or noexcept) but is known
- by the compiler to never throw an exception.
-
- CRITICAL
-
+ Warn when a noexcept-expression evaluates to false because of a call
+to a function that does not have a non-throwing exception
+specification (i.e. throw()
or noexcept
) but is known by
+the compiler to never throw an exception.
+]]>
+
+
-Wnoexcept-type
- Warn if the C++1z feature making noexcept part of a function type changes the mangled name of a symbol relative to C++14
+ Warn if C++17 noexcept function type will change the mangled name of a symbol
- Warn if the C++1z feature making noexcept part of a function type changes the mangled name of a
- symbol relative to C++14. Enabled by -Wabi and -Wc++1z-compat.
-
- CRITICAL
-
+ Warn if the C++17 feature making noexcept
part of a function
+type changes the mangled name of a symbol relative to C++14. Enabled
+by -Wabi and -Wc++17-compat.
+
+As an example:
+
+
+
template <class T> void f(T t) { t(); };
+void g() noexcept;
+void h() { f(g); }
+
+In C++14, f
calls f<void(*)()>
, but in
+C++17 it calls f<void(*)()noexcept>
.
+
]]>
+
+
-Wnon-template-friend
Warn when non-templatized friend functions are declared within a template
- Disable warnings when non-templatized friend functions are declared within a template.
- Since the advent of explicit template specification support in G++, if the name of the friend is
- an unqualified-id (i.e., friend foo(int)), the C++ language specification demands that the friend
- declare or define an ordinary, nontemplate function. (Section 14.5.3). Before G++ implemented
- explicit specification, unqualified-ids could be interpreted as a particular specialization of a
- templatized function. Because this non-conforming behavior is no longer the default behavior for
- G++, -Wnon-template-friend allows the compiler to check existing code for potential trouble spots
- and is on by default. This new compiler behavior can be turned off with -Wno-non-template-friend,
- which keeps the conformant compiler code but disables the helpful warning.
-
- CRITICAL
-
+ Disable warnings when non-template friend functions are declared
+within a template. In very old versions of GCC that predate implementation
+of the ISO standard, declarations such as
+‘friend int foo(int)’, where the name of the friend is an unqualified-id,
+could be interpreted as a particular specialization of a template
+function; the warning exists to diagnose compatibility problems,
+and is enabled by default.
+]]>
+
+
-Wnon-virtual-dtor
Warn about non-virtual destructors
- Warn when a class has virtual functions and accessible non-virtual destructor, in which
- case it would be possible but unsafe to delete an instance of a derived class through a pointer
- to the base class.
-
- CRITICAL
-
+ Warn when a class has virtual functions and an accessible non-virtual
+destructor itself or in an accessible polymorphic base class, in which
+case it is possible but unsafe to delete an instance of a derived
+class through a pointer to the class itself or base class. This
+warning is automatically enabled if -Weffc++ is specified.
+The -Wdelete-non-virtual-dtor option (enabled by -Wall)
+should be preferred because it warns about the unsafe cases without false
+positives.
+]]>
+
+
-Wnonnull
Warn about NULL being passed to argument slots marked as requiring non-NULL
- Warn about passing a null pointer for arguments marked as requiring a non-null value
- by the "nonnull" function attribute.
-
- CRITICAL
-
+ Warn about passing a null pointer for arguments marked as
+requiring a non-null value by the nonnull
function attribute.
+
+-Wnonnull is included in -Wall and -Wformat. It
+can be disabled with the -Wno-nonnull option.
+
]]>
+
+
-Wnonnull-compare
- Warn when comparing an argument marked with the nonnull function attribute against null inside the function.
+ Warn if comparing pointer parameter with nonnull attribute with NULL
- Warn when comparing an argument marked with the nonnull function attribute against null
- inside the function.
-
- -Wnonnull-compare is included in -Wall. It can be disabled with the -Wno-nonnull-compare
- option.
-
- CRITICAL
-
+ Warn when comparing an argument marked with the nonnull
+function attribute against null inside the function.
+
+-Wnonnull-compare is included in -Wall. It
+can be disabled with the -Wno-nonnull-compare option.
+
]]>
+
+
-Wnormalized
- Warn about non-normalised Unicode strings
-
- In ISO C and ISO C++, two identifiers are different if they are different sequences
- of characters. However, sometimes when characters outside the basic ASCII character set are used,
- you can have two different character sequences that look the same. To avoid confusion, the ISO
- 10646 standard sets out some normalization rules which when applied ensure that two sequences that
- look the same are turned into the same sequence. GCC can warn you if you are using identifiers
- that have not been normalized; this option controls that warning.
-
- There are four levels of warning supported by GCC. The default is -Wnormalized=nfc, which warns
- about any identifier that is not in the ISO 10646 "C" normalized form, NFC. NFC is the recommended
- form for most uses.
-
- Unfortunately, there are some characters allowed in identifiers by ISO C and ISO C++ that, when
- turned into NFC, are not allowed in identifiers. That is, there's no way to use these symbols in
- portable ISO C or C++ and have all your identifiers in NFC. -Wnormalized=id suppresses the warning
- for these characters. It is hoped that future versions of the standards involved will correct
- this, which is why this option is not the default.
-
- You can switch the warning off for all characters by writing -Wnormalized=none. You would only
- want to do this if you were using some other normalization scheme (like "D"), because otherwise
- you can easily create bugs that are literally impossible to see.
-
- Some characters in ISO 10646 have distinct meanings but look identical in some fonts or display
- methodologies, especially once formatting has been applied. For instance "\u207F", "SUPERSCRIPT
- LATIN SMALL LETTER N", will display just like a regular "n" that has been placed in a superscript.
- ISO 10646 defines the NFKC normalization scheme to convert all these into a standard form as well,
- and GCC will warn 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 is unable to be fixed to display these characters distinctly.
-
- CRITICAL
-
+ Warn about non-normalized Unicode strings
+
+ In ISO C and ISO C++, two identifiers are different if they are
+different sequences of characters. However, sometimes when characters
+outside the basic ASCII character set are used, you can have two
+different character sequences that look the same. To avoid confusion,
+the ISO 10646 standard sets out some normalization rules which
+when applied ensure that two sequences that look the same are turned into
+the same sequence. GCC can warn you if you are using identifiers that
+have not been normalized; this option controls that warning.
+
+There are four levels of warning supported by GCC. The default is
+-Wnormalized=nfc, which warns about any identifier that is
+not in the ISO 10646 “C” normalized form, NFC. NFC is the
+recommended form for most uses. It is equivalent to
+-Wnormalized.
+
+Unfortunately, there are some characters allowed in identifiers by
+ISO C and ISO C++ that, when turned into NFC, are not allowed in
+identifiers. That is, there’s no way to use these symbols in portable
+ISO C or C++ and have all your identifiers in NFC.
+-Wnormalized=id suppresses the warning for these characters.
+It is hoped that future versions of the standards involved will correct
+this, which is why this option is not the default.
+
+You can switch the warning off for all characters by writing
+-Wnormalized=none or -Wno-normalized. You should
+only do this if you are using some other normalization scheme (like
+“D”), because otherwise you can easily create bugs that are
+literally impossible to see.
+
+Some characters in ISO 10646 have distinct meanings but look identical
+in some fonts or display methodologies, especially once formatting has
+been applied. For instance \u207F
, “SUPERSCRIPT LATIN SMALL
+LETTER N”, displays just like a regular n
that has been
+placed in a superscript. ISO 10646 defines the NFKC
+normalization scheme to convert all these into a standard form as
+well, and GCC warns if your code is not in NFKC if you use
+-Wnormalized=nfkc. This warning is comparable to warning
+about every identifier that contains the letter O because it might be
+confused with the digit 0, and so is not the default, but may be
+useful as a local coding convention if the programming environment
+cannot be fixed to display these characters distinctly.
+
]]>
+
+
+
+ -Wnrvo
+ Warn if the named return value optimization is not performed although it is allowed
+
+ Warn if the compiler does not elide the copy from a local variable to
+the return value of a function in a context where it is allowed by
+[class.copy.elision]. This elision is commonly known as the Named
+Return Value Optimization. For instance, in the example below the
+compiler cannot elide copies from both v1 and v2, so it elides neither.
+
+
+
std::vector<int> f()
+{
+ std::vector<int> v1, v2;
+ // ...
+ if (cond) return v1;
+ else return v2; // warning: not eliding copy
+}
+
]]>
+
+
-Wnull-dereference
- Warn if the compiler detects paths that trigger erroneous or undefined behavior due to dereferencing a null pointer.
-
- 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.
-
- CRITICAL
-
+ Warn if dereferencing a NULL pointer may lead to erroneous or undefined behavior
+
+ 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.
+]]>
+
+
+
+ -Wobjc-root-class
+ Warn if a class interface has no superclass
+
+ 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))
.
+]]>
+
+
+
+ -Wodr
+ Warn about some C++ One Definition Rule violations during link time optimization
+
+ Warn about One Definition Rule violations during link-time optimization.
+Enabled by default.
+]]>
+
+
-Wold-style-cast
Warn if a C-style cast is used in a program
- Warn if an old-style (C-style) cast to a non-void type is used within a C++ program.
- The new-style casts (dynamic_cast, static_cast, reinterpret_cast, and const_cast) are less vulnerable
- to unintended effects and much easier to search for.
-
- CRITICAL
-
+ Warn if an old-style (C-style) cast to a non-void type is used within
+a C++ program. The new-style casts (dynamic_cast
,
+static_cast
, reinterpret_cast
, and const_cast
) are
+less vulnerable to unintended effects and much easier to search for.
+]]>
+
+
-Wold-style-declaration
Warn for obsolescent usage in a declaration
- 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.
-
- CRITICAL
-
+ 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
Warn if an old-style parameter definition is used
- Warn if an old-style function definition is used. A warning is given even if there
- is a previous prototype.
-
- CRITICAL
-
+ 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.
+]]>
+
+
+
+ -Wopenacc-parallelism
+ Warn about potentially suboptimal choices related to OpenACC parallelism
+
+ Warn about potentially suboptimal choices related to OpenACC parallelism.
+]]>
+
+
+
+ -Wopenmp
+ Warn about suspicious OpenMP code
+
+ Warn about suspicious OpenMP code.
+]]>
+
+
+
+ -Wopenmp-simd
+ Warn if a simd directive is overridden by the vectorizer cost model
+
+ 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.
+]]>
+
+
-Woverflow
Warn about overflow in arithmetic expressions
- Warn about compile-time overflow in constant expressions.
-
- CRITICAL
-
+ Warn about compile-time overflow in constant expressions.
+]]>
+
+
-Woverlength-strings
Warn if a string is longer than the maximum portable length specified by the standard
- Warn about string constants that are longer than the "minimum maximum" length specified
- in the C standard. Modern compilers generally allow string constants that are much longer than the
- standard's minimum limit, but very portable programs should avoid using longer strings.
-
- The limit applies after string constant concatenation, and does not count the trailing NUL. In C90,
- the limit was 509 characters; in C99, it was raised to 4095. C++98 does not specify a normative
- minimum maximum, so we do not diagnose overlength strings in C++.
-
- CRITICAL
-
+ Warn about string constants that are longer than the “minimum
+maximum” length specified in the C standard. Modern compilers
+generally allow string constants that are much longer than the
+standard’s minimum limit, but very portable programs should avoid
+using longer strings.
+
+The limit applies after string constant concatenation, and does
+not count the trailing NUL. In C90, the limit was 509 characters; in
+C99, it was raised to 4095. C++98 does not specify a normative
+minimum maximum, so we do not diagnose overlength strings in C++.
+
+This option is implied by -Wpedantic, and can be disabled with
+-Wno-overlength-strings.
+
]]>
+
+
-Woverloaded-virtual
Warn about overloaded virtual function names
- Warn when a function declaration hides virtual functions from a base class. For example, in:
-
- struct A {
- virtual void f();
- };
-
- struct B: public A {
- void f(int);
- };
-
- the "A" class version of "f" is hidden in "B", and code like:
-
- B* b;
- b->f();
-
- will fail to compile.
-
- CRITICAL
-
+ Warn when a function declaration hides virtual functions from a
+base class. For example, in:
+
+
+
struct A {
+ virtual void f();
+};
+
+struct B: public A {
+ void f(int); // does not override
+};
+
+the A
class version of f
is hidden in B
, and code
+like:
+
+
+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.
+
]]>
+
+
-Woverride-init
Warn about overriding initializers without side effects
- Warn if an initialized field without side effects is overridden when using designated
- initializers.
-
- CRITICAL
-
+ Warn if an initialized field without side effects is overridden when
+using designated initializers (see Designated
+Initializers).
+
+This warning is included in -Wextra. To get other
+-Wextra warnings without this one, use -Wextra
+-Wno-override-init.
+
]]>
+
+
-Woverride-init-side-effects
- Warn if an initialized field with side effects is overridden when using designated initializers
+ Warn about overriding initializers with side effects
- Warn if an initialized field with side effects is overridden when using designated initializers.
-
- CRITICAL
-
+ Warn if an initialized field with side effects is overridden when
+using designated initializers (see Designated
+Initializers). This warning is enabled by default.
+]]>
+
+
-Wpacked
Warn when the packed attribute has no effect on struct layout
- Warn if a structure is given the packed attribute, but the packed attribute has no
- effect on the layout or size of the structure. Such structures may be mis-aligned for little benefit.
- For instance, in this code, the variable "f.x" in "struct bar" will be 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;
- };
-
- CRITICAL
-
+ Warn if a structure is given the packed attribute, but the packed
+attribute has no effect on the layout or size of the structure.
+Such structures may be mis-aligned for little benefit. For
+instance, in this code, the variable f.x
in struct bar
+is misaligned even though struct bar
does not itself
+have the packed attribute:
+
+
+
struct foo {
+ int x;
+ char a, b, c, d;
+} __attribute__((packed));
+struct bar {
+ char z;
+ struct foo f;
+};
+
]]>
+
+
-Wpacked-bitfield-compat
Warn about packed bit-fields whose offset changed in GCC 4.4
- The 4.1, 4.2 and 4.3 series of GCC ignore the "packed" attribute on bit-fields of
- type "char". This has been 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));
-
- CRITICAL
-
+ 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
+ Warn when fields in a struct with the packed attribute are misaligned
+
+ 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 when padding is required to align structure members
- 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.
-
- CRITICAL
-
+ 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.
+]]>
+
+
-Wparentheses
Warn about possibly missing parentheses
- Warn if parentheses are omitted in certain contexts, such as when there is an
- assignment in a context where a truth value is expected, or when operators are nested whose
- precedence people often get confused about.
-
- Also warn if a comparison like x<=y<=z appears; this is equivalent to (x<=y ? 1 : 0) <= z, which
- is a different interpretation from that of ordinary mathematical notation.
-
- Also warn about constructions where there may be confusion to which "if" statement an "else"
- branch belongs. Here is an example of such a case:
-
- {
- if (a)
- if (b)
- foo ();
- else
- bar ();
- }
-
- In C/C++, every "else" branch belongs to the innermost possible "if" statement, which in this
- example is "if (b)". This is often not what the programmer expected, as illustrated in the above
- example by indentation the programmer chose. When there is the potential for this confusion, GCC
- will issue a warning when this flag is specified. To eliminate the warning, add explicit braces
- around the innermost "if" statement so there is no way the "else" could belong to the enclosing
- "if". The resulting code would look like this:
-
- {
- if (a)
- {
- if (b)
- foo ();
- else
- bar ();
- }
- }
-
- Also warn for dangerous uses of the ?: with omitted middle operand GNU extension. When the condition
- in the ?: operator is a boolean expression the omitted value will be always 1. Often the user
- expects it to be a value computed inside the conditional expression instead.
-
- CRITICAL
-
-
- -Wplacement-new
- Warn about placement new expressions with undefined behavior
-
- Warn about placement new expressions with undefined behavior, such as constructing an object in a
- buffer that is smaller than the type of the object. For example, the placement new expression below
- is diagnosed because it attempts to construct an array of 64 integers in a buffer only 64 bytes large.
-
- char buf [64];
- new (buf) int[64];
-
- This warning is enabled by default.
-
- -Wplacement-new=1
-
- This is the default warning level of -Wplacement-new. At this level the warning is not issued for
- some strictly undefined constructs that GCC allows as extensions for compatibility with legacy
- code. For example, the following new expression is not diagnosed at this level even though it has
- undefined behavior according to the C++ standard because it writes past the end of the one-element
- array.
-
- struct S { int n, a[1]; };
- S *s = (S *)malloc (sizeof *s + 31 * sizeof s->a[0]);
- new (s->a)int [32]();
-
- -Wplacement-new=2
-
- At this level, in addition to diagnosing all the same constructs as at level 1, a diagnostic is
- also issued for placement new expressions that construct an object in the last member of structure
- whose type is an array of a single element and whose size is less than the size of the object being
- constructed. While the previous example would be diagnosed, the following construct makes use of the
- flexible member array extension to avoid the warning at level 2.
-
- struct S { int n, a[]; };
- S *s = (S *)malloc (sizeof *s + 32 * sizeof s->a[0]);
- new (s->a)int [32]();
-
-
- CRITICAL
-
+ Warn if parentheses are omitted in certain contexts, such
+as when there is an assignment in a context where a truth value
+is expected, or when operators are nested whose precedence people
+often get confused about.
+
+Also warn if a comparison like x<=y<=z
appears; this is
+equivalent to (x<=y ? 1 : 0) <= z
, which is a different
+interpretation from that of ordinary mathematical notation.
+
+Also warn for dangerous uses of the GNU extension to
+?:
with omitted middle operand. When the condition
+in the ?
: operator is a boolean expression, the omitted value is
+always 1. Often programmers expect it to be a value computed
+inside the conditional expression instead.
+
+For C++ this also warns for some cases of unnecessary parentheses in
+declarations, which can indicate an attempt at a function call instead
+of a declaration:
+
+
{
+ // Declares a local variable called mymutex.
+ std::unique_lock<std::mutex> (mymutex);
+ // User meant std::unique_lock<std::mutex> lock (mymutex);
+}
+
+This warning is enabled by -Wall.
+
]]>
+
+
+
+ -Wpedantic
+ Issue warnings needed for strict compliance to the standard
+
+ Issue all the warnings demanded by strict ISO C and ISO C++;
+diagnose all programs that use forbidden extensions, and some other
+programs that do not follow ISO C and ISO C++. This follows the version
+of the ISO C or C++ standard specified by any -std option used.
+
+Valid ISO C and ISO C++ programs should compile properly with or without
+this option (though a rare few require -ansi or a
+-std option specifying the version of the standard). However,
+without this option, certain GNU extensions and traditional C and C++
+features are supported as well. With this option, they are diagnosed
+(or rejected with -pedantic-errors).
+
+-Wpedantic does not cause warning messages for use of the
+alternate keywords whose names begin and end with ‘__’. This alternate
+format can also be used to disable warnings for non-ISO ‘__intN’ types,
+i.e. ‘__intN__’.
+Pedantic warnings are also disabled in the expression that follows
+__extension__
. However, only system header files should use
+these escape routes; application programs should avoid them.
+See Alternate Keywords.
+
+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.)
+
]]>
+
+
+
+ -Wpedantic-ms-format
+ Warn about none ISO msvcrt scanf/printf width extensions
+
+ When used in combination with -Wformat
+and -pedantic without GNU extensions, this option
+disables the warnings about non-ISO printf
/ scanf
format
+width specifiers I32
, I64
, and I
used on Windows targets,
+which depend on the MS runtime.
+]]>
+
+
+
+ -Wpessimizing-move
+ Warn about calling std::move on a local object in a return statement preventing copy elision
+
+ 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.
+
]]>
+
+
+
+ -Wplacement-new
+ Warn for placement new expressions with undefined behavior
+
+ Warn about placement new expressions with undefined behavior, such as
+constructing an object in a buffer that is smaller than the type of
+the object. For example, the placement new expression below is diagnosed
+because it attempts to construct an array of 64 integers in a buffer only
+64 bytes large.
+
+
char buf [64];
+new (buf) int[64];
+
+This warning is enabled by default.
+
+
+-Wplacement-new=1
+This is the default warning level of -Wplacement-new. At this
+level the warning is not issued for some strictly undefined constructs that
+GCC allows as extensions for compatibility with legacy code. For example,
+the following new
expression is not diagnosed at this level even
+though it has undefined behavior according to the C++ standard because
+it writes past the end of the one-element array.
+
+
struct S { int n, a[1]; };
+S *s = (S *)malloc (sizeof *s + 31 * sizeof s->a[0]);
+new (s->a)int [32]();
+
+
+-Wplacement-new=2
+At this level, in addition to diagnosing all the same constructs as at level
+1, a diagnostic is also issued for placement new expressions that construct
+an object in the last member of structure whose type is an array of a single
+element and whose size is less than the size of the object being constructed.
+While the previous example would be diagnosed, the following construct makes
+use of the flexible member array extension to avoid the warning at level 2.
+
+
struct S { int n, a[]; };
+S *s = (S *)malloc (sizeof *s + 32 * sizeof s->a[0]);
+new (s->a)int [32]();
+
+
+
]]>
+
+
-Wpmf-conversions
Warn when converting the type of pointers to member functions
- Warn when converting a bound pointer to member function to a plain pointer.
-
- CRITICAL
-
+ Disable the diagnostic for converting a bound pointer to member function
+to a plain pointer.
+]]>
+
+
-Wpointer-arith
Warn about function pointer arithmetic
- Warn about anything that depends on the "size of" a function type or of "void". GNU
- C assigns these types a size of 1, for convenience in calculations with "void *" pointers and
- pointers to functions. In C++, warn also when an arithmetic operation involves "NULL".
-
- CRITICAL
-
+ Warn about anything that depends on the “size of” a function type or
+of void
. GNU C assigns these types a size of 1, for
+convenience in calculations with void *
pointers and pointers
+to functions. In C++, warn also when an arithmetic operation involves
+NULL
. This warning is also enabled by -Wpedantic.
+
+This warning is upgraded to an error by -pedantic-errors.
+
]]>
+
+
-Wpointer-compare
- Warn if a pointer is compared with a zero character constant
+ Warn when a pointer is compared with a zero character constant
- Warn if a pointer is compared with a zero character constant. This usually means that the
- pointer was meant to be dereferenced. For example:
-
- const char *p = foo ();
- if (p == '\0')
- return 42;
-
- Note that the code above is invalid in C++11.
-
- CRITICAL
-
+ Warn if a pointer is compared with a zero character constant.
+This usually
+means that the pointer was meant to be dereferenced. For example:
+
+
+
const char *p = foo ();
+if (p == '\0')
+ return 42;
+
+Note that the code above is invalid in C++11.
+
+This warning is enabled by default.
+
]]>
+
+
-Wpointer-sign
Warn when a pointer differs in signedness in an assignment
- Warn for pointer argument passing or assignment with different signedness. This option
- is only supported for C and Objective-C.
-
- CRITICAL
-
+ Warn for pointer argument passing or assignment with different signedness.
+This option is only supported for C and Objective-C. It is implied by
+-Wall and by -Wpedantic, which can be disabled with
+-Wno-pointer-sign.
+
+This warning is upgraded to an error by -pedantic-errors.
+
]]>
+
+
-Wpointer-to-int-cast
Warn when a pointer is cast to an integer of a different size
- Warn when casting casting from a pointer to an integer type of a different size.
-
- CRITICAL
-
+ Suppress warnings from casts from a pointer to an integer type of a
+different size.
+]]>
+
+
-Wpragmas
Warn about misuses of pragmas
- Warn about misuses of pragmas, such as incorrect parameters, invalid syntax, or
- conflicts between pragmas.
-
- CRITICAL
-
+ Warn about misuses of pragmas, such as incorrect parameters,
+invalid syntax, or conflicts between pragmas. See also
+-Wunknown-pragmas.
+]]>
+
+
+
+ -Wprio-ctor-dtor
+ Warn if constructor or destructors with priorities from 0 to 100 are used
+
+ 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.
+]]>
+
+
-Wproperty-assign-default
Warn if a property for an Objective-C object has no assign semantics specified
- Warn if a property for an Objective-C object has no assign semantics specified
-
- CRITICAL
-
+ Warn if a property for an Objective-C object has no assign
+semantics specified.
+]]>
+
+
-Wprotocol
Warn if inherited methods are unimplemented
- 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.
-
- CRITICAL
-
-
- -Wreal-q-constant
- Warn about real-literal-constants with 'q' exponent-letter
-
- Warn about real-literal-constants with 'q' exponent-letter
-
- CRITICAL
-
+ 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.
+]]>
+
+
+
+ -Wrange-loop-construct
+ Warn when a range-based for-loop is creating unnecessary copies
+
+ This warning warns when a C++ range-based for-loop is creating an unnecessary
+copy. This can happen when the range declaration is not a reference, but
+probably should be. For example:
+
+
+
struct S { char arr[128]; };
+void fn () {
+ S arr[5];
+ for (const auto x : arr) { … }
+}
+
+It does not warn when the type being copied is a trivially-copyable type whose
+size is less than 64 bytes.
+
+This warning also warns when a loop variable in a range-based for-loop is
+initialized with a value of a different type resulting in a copy. For example:
+
+
+
void fn() {
+ int arr[10];
+ for (const double &x : arr) { … }
+}
+
+In the example above, in every iteration of the loop a temporary value of
+type double
is created and destroyed, to which the reference
+const double &
is bound.
+
+This warning is enabled by -Wall.
+
]]>
+
+
-Wredundant-decls
Warn about multiple declarations of the same object
- Warn if anything is declared more than once in the same scope, even
- in cases where multiple declaration is valid and changes nothing.
-
- CRITICAL
-
+ Warn if anything is declared more than once in the same scope, even in
+cases where multiple declaration is valid and changes nothing.
+]]>
+
+
+
+ -Wredundant-move
+ Warn about redundant calls to std::move
+
+ This warning warns about redundant calls to std::move
; that is, when
+a move operation would have been performed even without the std::move
+call. This happens because the compiler is forced to treat the object as if
+it were an rvalue in certain situations such as returning a local variable,
+where copy elision isn’t applicable. Consider:
+
+
+
struct T {
+…
+};
+T fn(T t)
+{
+ …
+ return std::move (t);
+}
+
+Here, the std::move
call is redundant. Because G++ implements Core
+Issue 1579, another example is:
+
+
+
struct T { // convertible to U
+…
+};
+struct U {
+…
+};
+U fn()
+{
+ T t;
+ …
+ return std::move (t);
+}
+
+In this example, copy elision isn’t applicable because the type of the
+expression being returned and the function return type differ, yet G++
+treats the return value as if it were designated by an rvalue.
+
+This warning is enabled by -Wextra.
+
]]>
+
+
+
+ -Wredundant-tags
+ Warn when a class or enumerated type is referenced using a redundant class-key
+
+ Warn about redundant class-key and enum-key in references to class types
+and enumerated types in contexts where the key can be eliminated without
+causing an ambiguity. For example:
+
+
+
struct foo;
+struct foo *p; // warn that keyword struct can be eliminated
+
+On the other hand, in this example there is no warning:
+
+
+
struct foo;
+void foo (); // "hides" struct foo
+void bar (struct foo&); // no warning, keyword struct is necessary
+
]]>
+
+
-Wregister
- Warn on uses of the register storage class specifier, except when it is part of the GNU Explicit Register Variables extension
+ Warn about uses of register storage specifier
- Warn on uses of the register storage class specifier, except when it is part of the GNU Explicit
- Register Variables extension. The use of the register keyword as storage class specifier has been
- deprecated in C++11 and removed in C++17. Enabled by default with -std=c++1z.
-
- CRITICAL
-
+ Warn on uses of the register
storage class specifier, except
+when it is part of the GNU Variables in Specified Registers extension.
+The use of the register
keyword as storage class specifier has
+been deprecated in C++11 and removed in C++17.
+Enabled by default with -std=c++17.
+]]>
+
+
-Wreorder
Warn when the compiler reorders code
- Warn when the order of member initializers given in the code does not match the order
- in which they must be executed. For instance:
-
- struct A {
- int i;
- int j;
- A(): j (0), i (1) { }
- };
-
- The compiler will rearrange the member initializers for i and j to match the declaration order of
- the members, emitting a warning to that effect.
-
- CRITICAL
-
+ Warn when the order of member initializers given in the code does not
+match the order in which they must be executed. For instance:
+
+
+
struct A {
+ int i;
+ int j;
+ A(): j (0), i (1) { }
+};
+
+The compiler rearranges the member initializers for i
+and j
to match the declaration order of the members, emitting
+a warning to that effect. This warning is enabled by -Wall.
+
]]>
+
+
-Wrestrict
Warn when an argument passed to a restrict-qualified parameter aliases with another argument
- Warn when an argument passed to a restrict-qualified parameter aliases with another argument.
-
- CRITICAL
-
+ Warn when an object referenced by a restrict
-qualified parameter
+(or, in C++, a __restrict
-qualified parameter) is aliased by another
+argument, or when copies between such objects overlap. For example,
+the call to the strcpy
function below attempts to truncate the string
+by replacing its initial characters with the last four. However, because
+the call writes the terminating NUL into a[4]
, the copies overlap and
+the call is diagnosed.
+
+
+
void foo (void)
+{
+ char a[] = "abcd1234";
+ strcpy (a, a + 4);
+ …
+}
+
+The -Wrestrict option detects some instances of simple overlap
+even without optimization but works best at -O2 and above. It
+is included in -Wall.
+
]]>
+
+
+
+ -Wreturn-local-addr
+ Warn about returning a pointer/reference to a local or temporary variable
+
+ 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 whenever void-returning functions return a non-void expressions, or a return expression is missing in a function not returning void
+
+ 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's return type defaults to "int" (C), or about inconsistent return types (C++)
- Warn whenever a function is defined with a return-type that defaults to "int". Also
- warn about any "return" statement with no return-value in a function whose return-type is not "void"
- (falling off the end of the function body is considered returning without a value), and about a
- "return" statement with an expression in a function whose return- type is "void".
-
- For C++, a function without return type always produces a diagnostic message, even when
- -Wno-return-type is specified. The only exceptions are main and functions defined in system headers.
-
- CRITICAL
-
+ Warn whenever a function is defined with a return type that defaults to
+int
(unless -Wimplicit-int is active, which takes
+precedence). Also warn if execution may reach the end of the function
+body, or if the function does not contain any return statement at all.
+
+Attempting to use the return value of a non-void
function other
+than main
that flows off the end by reaching the closing curly
+brace that terminates the function is undefined.
+
+Unlike in C, in C++, flowing off the end of a non-void
function other
+than main
results in undefined behavior even when the value of
+the function is not used.
+
+This warning is enabled by default in C++ and by -Wall otherwise.
+
]]>
+
+
+
+ -Wscalar-storage-order
+ Warn on suspicious constructs involving reverse scalar storage order
+
+ Warn on suspicious constructs involving reverse scalar storage order.
+]]>
+
+
-Wselector
Warn if a selector has multiple methods
- Warn if multiple methods of different types for the same selector are found during
- compilation. The check is performed on the list of methods in the final stage of compilation.
- Additionally, a check is performed for each selector appearing in a "@selector(...)" expression,
- and a corresponding method for that selector has been found during compilation. Because these
- checks scan the method table only at the end of compilation, these warnings are not produced if
- the final stage of compilation is not reached, for example because an error is found during
- compilation, or because the -fsyntax-only option is being used.
-
- CRITICAL
-
+ Warn if multiple methods of different types for the same selector are
+found during compilation. The check is performed on the list of methods
+in the final stage of compilation. Additionally, a check is performed
+for each selector appearing in a @selector(…)
+expression, and a corresponding method for that selector has been found
+during compilation. Because these checks scan the method table only at
+the end of compilation, these warnings are not produced if the final
+stage of compilation is not reached, for example because an error is
+found during compilation, or because the -fsyntax-only option is
+being used.
+]]>
+
+
+
+ -Wself-move
+ Warn when a value is moved to itself with std::move
+
+ This warning warns when a value is moved to itself with std::move
.
+Such a std::move
typically has no effect.
+
+
+
struct T {
+…
+};
+void fn()
+{
+ T t;
+ …
+ t = std::move (t);
+}
+
+This warning is enabled by -Wall.
+
]]>
+
+
-Wsequence-point
Warn about possible violations of sequence point rules
- Warn about code that may have undefined semantics because of violations of sequence
- point rules in the C and C++ standards.
-
- The C and C++ standards defines the order in which expressions in a C/C++ program are evaluated
- in terms of sequence points, which represent a partial ordering between the execution of parts of
- the program: those executed before the sequence point, and those executed after it. These occur
- after the evaluation of a full expression (one which is not part of a larger expression), after
- the evaluation of the first operand of a "&&", "||", "? :" or "," (comma) operator, before a
- function is called (but after the evaluation of its arguments and the expression denoting the
- called function), and in certain other places. Other than as expressed by the sequence point
- rules, the order of evaluation of subexpressions of an expression is not specified. All these
- rules describe only a partial order rather than a total order, since, for example, if two functions
- are called within one expression with no sequence point between them, the order in which the
- functions are called is not specified. However, the standards committee have ruled that function
- calls do not overlap.
-
- It is not specified when between sequence points modifications to the values of objects take effect.
- Programs whose behavior depends on this have undefined behavior; the C and C++ standards specify
- that "Between the previous and next sequence point an object shall have its stored value modified
- at most once by the evaluation of an expression. Furthermore, the prior value shall be read only
- to determine the value to be stored.". If a program breaks these rules, the results on any
- particular implementation are entirely unpredictable.
-
- Examples of code with undefined behavior are "a = a++;", "a[n] = b[n++]" and "a[i++] = i;". Some
- more complicated cases are not diagnosed by this option, and it may give an occasional false
- positive result, but in general it has been found fairly effective at detecting this sort of
- problem in programs.
-
- The standard is worded confusingly, therefore there is some debate over the precise meaning of the
- sequence point rules in subtle cases. Links to discussions of the problem, including proposed
- formal definitions, may be found on the GCC readings page, at http://gcc.gnu.org/readings.html.
-
- CRITICAL
-
+ Warn about code that may have undefined semantics because of violations
+of sequence point rules in the C and C++ standards.
+
+The C and C++ standards define the order in which expressions in a C/C++
+program are evaluated in terms of sequence points, which represent
+a partial ordering between the execution of parts of the program: those
+executed before the sequence point, and those executed after it. These
+occur after the evaluation of a full expression (one which is not part
+of a larger expression), after the evaluation of the first operand of a
+&&
, ||
, ? :
or ,
(comma) operator, before a
+function is called (but after the evaluation of its arguments and the
+expression denoting the called function), and in certain other places.
+Other than as expressed by the sequence point rules, the order of
+evaluation of subexpressions of an expression is not specified. All
+these rules describe only a partial order rather than a total order,
+since, for example, if two functions are called within one expression
+with no sequence point between them, the order in which the functions
+are called is not specified. However, the standards committee have
+ruled that function calls do not overlap.
+
+It is not specified when between sequence points modifications to the
+values of objects take effect. Programs whose behavior depends on this
+have undefined behavior; the C and C++ standards specify that “Between
+the previous and next sequence point an object shall have its stored
+value modified at most once by the evaluation of an expression.
+Furthermore, the prior value shall be read only to determine the value
+to be stored.”. If a program breaks these rules, the results on any
+particular implementation are entirely unpredictable.
+
+Examples of code with undefined behavior are a = a++;
, a[n]
+= b[n++]
and a[i++] = i;
. Some more complicated cases are not
+diagnosed by this option, and it may give an occasional false positive
+result, but in general it has been found fairly effective at detecting
+this sort of problem in programs.
+
+The C++17 standard will define the order of evaluation of operands in
+more cases: in particular it requires that the right-hand side of an
+assignment be evaluated before the left-hand side, so the above
+examples are no longer undefined. But this option will still warn
+about them, to help people avoid writing code that is undefined in C
+and earlier revisions of C++.
+
+The standard is worded confusingly, therefore there is some debate
+over the precise meaning of the sequence point rules in subtle cases.
+Links to discussions of the problem, including proposed formal
+definitions, may be found on the GCC readings page, at
+https://gcc.gnu.org/readings.html.
+
+This warning is enabled by -Wall for C and C++.
+
]]>
+
+
-Wshadow
- Warn when one local variable shadows another
-
- Warn whenever a local variable or type declaration shadows another variable, parameter,
- type, or class member (in C++), or whenever a built-in function is shadowed. Note that in C++,
- the compiler will not warn if a local variable shadows a struct/class/enum, but will warn if it
- shadows an explicit typedef.
-
- CRITICAL
-
+ Warn when one variable shadows another
+
+ 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.
+]]>
+
+
+
+ -Wshadow-ivar
+ Warn if a local declaration hides an instance variable
+
+ Warn whenever a local variable shadows an instance variable in an
+Objective-C method.
+]]>
+
+
-Wshift-count-negative
Warn if shift count is negative
- Warn if shift count is negative
-
- CRITICAL
-
+ Controls warnings if a shift count is negative.
+This warning is enabled by default.
+]]>
+
+
-Wshift-count-overflow
Warn if shift count >= width of type
- Warn if shift count >= width of type
-
- CRITICAL
-
+ 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
- Warn if left shifting a negative value. This warning is enabled by -Wextra in C99 and C++11
- modes (and newer).
-
- CRITICAL
-
+ Warn if left shifting a negative value. This warning is enabled by
+-Wextra in C99 (and newer) and C++11 to C++17 modes.
+]]>
+
+
-Wshift-overflow
- Warn about left shift overflows
+ Warn if left shift of a signed value overflows
- Warn about left shift overflows. This warning is enabled by default in C99 and C++11 modes
- (and newer).
-
- -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.)
-
- -Wshift-overflow=2
-
- This warning level also warns about left-shifting 1 into the sign bit, unless C++14 mode is
- active.
-
- CRITICAL
-
+ 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.
+
+
]]>
+
+
-Wsign-compare
Warn about signed-unsigned comparisons
- Warn when a comparison between signed and unsigned values could produce an incorrect
- result when the signed value is converted to unsigned.
-
- CRITICAL
-
+ 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 about signed-unsigned conversion
+ Warn for implicit type conversions between signed and unsigned integers
- 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.
-
- CRITICAL
-
+ 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.
+]]>
+
+
-Wsign-promo
Warn when overload promotes from unsigned to signed
- Warn when overload resolution chooses a promotion from unsigned or enumerated type
- to a signed type, over a conversion to an unsigned type of the same size. Previous versions of
- G++ would try to preserve unsignedness, but the standard mandates the current behavior.
-
- struct A {
- operator int ();
- A& operator = (int);
- };
-
- main ()
- {
- A a,b;
- a = b;
- }
-
- In this example, G++ will synthesize a default A& operator = (const A&);, while cfront will use
- the user-defined operator =.
-
- CRITICAL
-
+ Warn when overload resolution chooses a promotion from unsigned or
+enumerated type to a signed type, over a conversion to an unsigned type of
+the same size. Previous versions of G++ tried to preserve
+unsignedness, but the standard mandates the current behavior.
+]]>
+
+
-Wsized-deallocation
- Warn about a definition of an unsized deallocation function
-
- Warn about a definition of an unsized deallocation function
-
- void operator delete (void *) noexcept;
- void operator delete[] (void *) noexcept;
-
- without a definition of the corresponding sized deallocation function
-
- void operator delete (void *, std::size_t) noexcept;
- void operator delete[] (void *, std::size_t) noexcept;
-
- or vice versa. Enabled by -Wextra along with -fsized-deallocation.
-
- CRITICAL
-
+ Warn about missing sized deallocation functions
+
+ Warn about a definition of an unsized deallocation function
+
+
void operator delete (void *) noexcept;
+void operator delete[] (void *) noexcept;
+
+without a definition of the corresponding sized deallocation function
+
+
void operator delete (void *, std::size_t) noexcept;
+void operator delete[] (void *, std::size_t) noexcept;
+
+or vice versa. Enabled by -Wextra along with
+-fsized-deallocation.
+
]]>
+
+
-Wsizeof-array-argument
- Warn when the sizeof operator is applied to a parameter that is declared as an array in a function definition
-
- 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.
-
- CRITICAL
-
+ Warn when sizeof is applied on a parameter declared as an array
+
+ 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.
+]]>
+
+
+
+ -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
+
+ 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
+ Warn about suspicious divisions of two sizeof expressions that don't work correctly with pointers
- 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.
-
- CRITICAL
-
+ 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
-
- Warn for suspicious length parameters to certain string and memory
- built-in functions if the argument uses sizeof. This warning warns e.g.
- about 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));.
-
- This warning is enabled by -Wall
-]]>
-
- CRITICAL
-
+ Warn about suspicious length parameters to certain string functions if the argument uses sizeof
+
+ Warn for suspicious length parameters to certain string and memory built-in
+functions if the argument uses sizeof
. This warning triggers for
+example for memset (ptr, 0, sizeof (ptr));
if ptr
is not
+an array, but a pointer, and suggests a possible fix, or about
+memcpy (&foo, ptr, sizeof (&foo));
. -Wsizeof-pointer-memaccess
+also warns about calls to bounded string copy functions like strncat
+or strncpy
that specify as the bound a sizeof
expression of
+the source array. For example, in the following function the call to
+strncat
specifies the size of the source string as the bound. That
+is almost certainly a mistake and so the call is diagnosed.
+
+
void make_file (const char *name)
+{
+ char path[PATH_MAX];
+ strncpy (path, name, sizeof path - 1);
+ strncat (path, ".text", sizeof ".text");
+ …
+}
+
+The -Wsizeof-pointer-memaccess option is enabled by -Wall.
+
]]>
+
+
-Wstack-protector
Warn when not issuing stack smashing protection for some reason
- Warns about functions that will not be protected against stack smashing.This option
- is only active when -fstack-protector is active.
-
- CRITICAL
-
+ This option is only active when -fstack-protector is active. It
+warns about functions that are not protected against stack smashing.
+]]>
+
+
-Wstack-usage
- Warn if stack usage might be larger than specified amount
+ Warn if stack usage might exceed <byte-size>
- Warn if the stack usage of a function might be larger than len bytes. The computation done to determine the stack
- usage is conservative. Any space allocated via "alloca", variable-length arrays, or related constructs is included by
- the compiler when determining whether or not to issue a warning.
-
- The message is in keeping with the output of -fstack-usage.
-
- * If the stack usage is fully static but exceeds the specified amount, it's:
-
- warning: stack usage is 1120 bytes
-
- * If the stack usage is (partly) dynamic but bounded, it's:
-
- warning: stack usage might be 1648 bytes
-
- * If the stack usage is (partly) dynamic and not bounded, it's:
-
- warning: stack usage might be unbounded
-
- CRITICAL
-
+ Warn if the stack usage of a function might exceed byte-size.
+The computation done to determine the stack usage is conservative.
+Any space allocated via alloca
, variable-length arrays, or related
+constructs is included by the compiler when determining whether or not to
+issue a warning.
+
+The message is in keeping with the output of -fstack-usage.
+
+
+- If the stack usage is fully static but exceeds the specified amount, it’s:
+
+
+
warning: stack usage is 1120 bytes
+
+ - If the stack usage is (partly) dynamic but bounded, it’s:
+
+
+
warning: stack usage might be 1648 bytes
+
+ - If the stack usage is (partly) dynamic and not bounded, it’s:
+
+
+
warning: stack usage might be unbounded
+
+
+-Wstack-usage=‘PTRDIFF_MAX’ is enabled by default.
+Warnings controlled by the option can be disabled either by specifying
+byte-size of ‘SIZE_MAX’ or more or by
+-Wno-stack-usage.
+
]]>
+
+
-Wstrict-aliasing
Warn about code which might break strict aliasing rules
-
- Warn about code which might break the strict aliasing rules that the compiler is using
- for optimization. The warning does not catch all cases, but does attempt to catch the more common
- pitfalls. Higher levels correspond to higher accuracy (fewer false positives). Higher levels also
- correspond to more effort, similar to the way -O works. -Wstrict-aliasing is equivalent to
- -Wstrict-aliasing=n, with n=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 frontend 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 frontend 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 frontend: "*(int*)&some_float". If optimization is enabled, it also runs in the
- backend, 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.
-]]>
-
- CRITICAL
-
+
+ This option is only active when -fstrict-aliasing is active.
+It warns about code that might break the strict aliasing rules that the
+compiler is using for optimization.
+Higher levels correspond to higher accuracy (fewer false positives).
+Higher levels also correspond to more effort, similar to the way -O
+works.
+-Wstrict-aliasing is equivalent to -Wstrict-aliasing=3.
+
+Level 1: Most aggressive, quick, least accurate.
+Possibly useful when higher levels
+do not warn but -fstrict-aliasing still breaks the code, as it has very few
+false negatives. However, it has many false positives.
+Warns for all pointer conversions between possibly incompatible types,
+even if never dereferenced. Runs in the front end only.
+
+Level 2: Aggressive, quick, not too precise.
+May still have many false positives (not as many as level 1 though),
+and few false negatives (but possibly more than level 1).
+Unlike level 1, it only warns when an address is taken. Warns about
+incomplete types. Runs in the front end only.
+
+Level 3 (default for -Wstrict-aliasing):
+Should have very few false positives and few false
+negatives. Slightly slower than levels 1 or 2 when optimization is enabled.
+Takes care of the common pun+dereference pattern in the front end:
+*(int*)&some_float
.
+If optimization is enabled, it also runs in the back end, where it deals
+with multiple statement cases using flow-sensitive points-to information.
+Only warns when the converted pointer is dereferenced.
+Does not warn about incomplete types.
+
]]>
+
+
+
+ -Wstrict-flex-arrays
+ Warn about improper usages of flexible array members according to the level of -fstrict-flex-arrays
+
+ Warn about improper usages of flexible array members
+according to the level of the strict_flex_array (level)
+attribute attached to the trailing array field of a structure if it’s
+available, otherwise according to the level of the option
+-fstrict-flex-arrays=level. See Common Variable Attributes,
+for more information about the attribute, and Options Controlling C Dialect for
+more information about the option. -Wstrict-flex-arrays
+is effective only when level is greater than 0.
+
+When level=1, warnings are issued for a trailing array reference
+of a structure that have 2 or more elements if the trailing array is referenced
+as a flexible array member.
+
+When level=2, in addition to level=1, additional warnings are
+issued for a trailing one-element array reference of a structure
+if the array is referenced as a flexible array member.
+
+When level=3, in addition to level=2, additional warnings are
+issued for a trailing zero-length array reference of a structure
+if the array is referenced as a flexible array member.
+
+This option is more effective when -ftree-vrp is active (the
+default for -O2 and above) but some warnings may be diagnosed
+even without optimization.
+
]]>
+
+
-Wstrict-null-sentinel
Warn about uncasted NULL used as sentinel
- Warn also about the use of an uncasted "NULL" as sentinel. When compiling only with
- GCC this is a valid sentinel, as "NULL" is defined to "__null". Although it is a null pointer
- constant not a null pointer, it is guaranteed to be of the same size as a pointer. But this use
- is not portable across different compilers.
-
- CRITICAL
-
+ Warn about the use of an uncasted NULL
as sentinel. When
+compiling only with GCC this is a valid sentinel, as NULL
is defined
+to __null
. Although it is a null pointer constant rather than a
+null pointer, it is guaranteed to be of the same size as a pointer.
+But this use is not portable across different compilers.
+]]>
+
+
-Wstrict-overflow
Warn about optimizations that assume that signed overflow is undefined
- Warn about cases where the compiler optimizes based on the assumption that signed
- overflow does not occur. Note that it does not warn about all cases where the code might overflow:
- it only warns about cases where the compiler implements some optimization. Thus this warning
- depends on the optimization level.
-
- An optimization which 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 which is not actually a problem. To help
- focus on important issues, several warning levels are defined. No warnings are issued for the use
- of undefined signed overflow when estimating how many iterations a loop will require, in particular
- when determining whether a loop will be executed at all.
-
- -Wstrict-overflow=1
- Warn about cases which are both questionable and easy to avoid. For example: "x + 1 > x"; with
- -fstrict-overflow, the compiler will simplify this to 1. This level of -Wstrict-overflow is
- enabled by -Wall; higher levels are not, and must be explicitly requested.
-
- -Wstrict-overflow=2
- Also warn about other cases where a comparison is simplified to a constant. For example:
- "abs (x) >= 0". This can only be simplified when -fstrict-overflow is in effect, 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" will
- be simplified to "x > 0".
-
- -Wstrict-overflow=4
- Also warn about other simplifications not covered by the above cases. For example: "(x * 10) / 5"
- will be 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" will be simplified to "x + 1 >= y". This is reported
- only at the highest warning level because this simplification applies to many comparisons,
- so this warning level will give a very large number of false positives.
-
- CRITICAL
-
+ This option is only active when signed overflow is undefined.
+It warns about cases where the compiler optimizes based on the
+assumption that signed overflow does not occur. Note that it does not
+warn about all cases where the code might overflow: it only warns
+about cases where the compiler implements some optimization. Thus
+this warning depends on the optimization level.
+
+An optimization that assumes that signed overflow does not occur is
+perfectly safe if the values of the variables involved are such that
+overflow never does, in fact, occur. Therefore this warning can
+easily give a false positive: a warning about code that is not
+actually a problem. To help focus on important issues, several
+warning levels are defined. No warnings are issued for the use of
+undefined signed overflow when estimating how many iterations a loop
+requires, in particular when determining whether a loop will be
+executed at all.
+
+
+-Wstrict-overflow=1
+Warn about cases that are both questionable and easy to avoid. For
+example the compiler simplifies
+x + 1 > x
to 1
. This level of
+-Wstrict-overflow is enabled by -Wall; higher levels
+are not, and must be explicitly requested.
+
+
+-Wstrict-overflow=2
+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 warning level because this simplification applies to many
+comparisons, so this warning level gives a very large number of
+false positives.
+
+
]]>
+
+
-Wstrict-prototypes
Warn about unprototyped function declarations
- 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.)
-
- CRITICAL
-
+ 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.)
+]]>
+
+
-Wstrict-selector-match
Warn if type signatures of candidate methods do not match exactly
- 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 will omit such
- warnings if any differences found are confined to types which share the same size and alignment.
-
- CRITICAL
-
+ 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.
+]]>
+
+
+
+ -Wstring-compare
+ Warn about calls to strcmp and strncmp used in equality expressions that are necessarily true or false due to the length of one and size of the other argument
+
+ 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.
+
]]>
+
+
-Wstringop-overflow
- Warn for calls to string manipulation functions such as memcpy and strcpy that are determined to overflow the destination buffer.
-
- 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 Object Size
- Checking. The argument is meaningful only for functions that operate on character arrays but
- not for raw memory functions like memcpy which always make use of Object Size type-0. The
- option also warns for calls that specify a size in excess of the largest possible object or
- at most SIZE_MAX / 2 bytes. The option produces the best results with optimization enabled
- but can detect a small subset of simple buffer overflows even without optimization in calls
- to the GCC built-in functions like __builtin_memcpy that correspond to the standard functions.
- In any case, the option warns about just a subset of buffer overflows detected by the
- corresponding overflow checking built-ins. For example, the option will issue 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)
- {
+ Under the control of Object Size type, warn about buffer overflow in string manipulation functions like memcpy and strcpy
+
+ 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 Object Size Checking.
+The argument is meaningful only for functions that operate on character arrays
+but not for raw memory functions like memcpy
which always make use
+of Object Size type-0. The option also warns for calls that specify a size
+in excess of the largest possible object or at most SIZE_MAX / 2
bytes.
+The option produces the best results with optimization enabled but can detect
+a small subset of simple buffer overflows even without optimization in
+calls to the GCC built-in functions like __builtin_memcpy
that
+correspond to the standard functions. In any case, the option warns about
+just a subset of buffer overflows detected by the corresponding overflow
+checking built-ins. For example, the option issues a warning for
+the strcpy
call below because it copies at least 5 characters
+(the string "blue"
including the terminating NUL) into the buffer
+of size 4.
+
+
+
enum Color { blue, purple, yellow };
+const char* f (enum Color clr)
+{
+ static char buf [4];
+ const char *str;
+ switch (clr)
+ {
case blue: str = "blue"; break;
case purple: str = "purple"; break;
case yellow: str = "yellow"; break;
- }
-
- return strcpy (buf, str); // warning here
- }
-
- Option -Wstringop-overflow=2 is enabled by default.
-
- -Wstringop-overflow
- -Wstringop-overflow=1
-
- The -Wstringop-overflow=1 option uses type-zero Object Size Checking to determine the sizes
- of destination objects. This is the default setting of the option. At this setting the option
- will not warn for writes past the end of subobjects of larger objects accessed by pointers
- unless the size of the largest surrounding object is known. When the destination may be one of
- several objects it is assumed to be the largest one of them. On Linux systems, when
- optimization is enabled at this setting the option warns for the same code as when the
- _FORTIFY_SOURCE macro is defined to a non-zero value.
-
- -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 will warn about overflows when writing to
- members of the largest complete objects whose exact size is known. It will, however, 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.
-
- -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.
-
- -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 will warn 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.
-
- CRITICAL
-
+ return strcpy (buf, str); // warning here
+}
+
+Option -Wstringop-overflow=2 is enabled by default.
+
+
+-
+
-Wstringop-overflow
¶
+-Wstringop-overflow=1
+The -Wstringop-overflow=1 option uses type-zero Object Size Checking
+to determine the sizes of destination objects. At this setting the option
+does not warn for writes past the end of subobjects of larger objects accessed
+by pointers unless the size of the largest surrounding object is known. When
+the destination may be one of several objects it is assumed to be the largest
+one of them. On Linux systems, when optimization is enabled at this setting
+the option warns for the same code as when the _FORTIFY_SOURCE
macro
+is defined to a non-zero value.
+
+
+-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.
+
+
+-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.
+
+
]]>
+
+
+
+ -Wstringop-overread
+ Warn about reading past the end of a source array in string manipulation functions like memchr and memcpy
+
+ 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.
+
]]>
+
+
+
+ -Wstringop-truncation
+ Warn about truncation in string manipulation functions like strncat and strncpy
+
+ Warn for calls to bounded string manipulation functions
+such as strncat
,
+strncpy
, and stpncpy
that may either truncate the copied string
+or leave the destination unchanged.
+
+In the following example, the call to strncat
specifies a bound that
+is less than the length of the source string. As a result, the copy of
+the source will be truncated and so the call is diagnosed. To avoid the
+warning use bufsize - strlen (buf) - 1)
as the bound.
+
+
+
void append (char *buf, size_t bufsize)
+{
+ strncat (buf, ".txt", 3);
+}
+
+As another example, the following call to strncpy
results in copying
+to d
just the characters preceding the terminating NUL, without
+appending the NUL to the end. Assuming the result of strncpy
is
+necessarily a NUL-terminated string is a common mistake, and so the call
+is diagnosed. To avoid the warning when the result is not expected to be
+NUL-terminated, call memcpy
instead.
+
+
+
void copy (char *d, const char *s)
+{
+ strncpy (d, s, strlen (s));
+}
+
+In the following example, the call to strncpy
specifies the size
+of the destination buffer as the bound. If the length of the source
+string is equal to or greater than this size the result of the copy will
+not be NUL-terminated. Therefore, the call is also diagnosed. To avoid
+the warning, specify sizeof buf - 1
as the bound and set the last
+element of the buffer to NUL
.
+
+
+
void copy (const char *s)
+{
+ char buf[80];
+ strncpy (buf, s, sizeof buf);
+ …
+}
+
+In situations where a character array is intended to store a sequence
+of bytes with no terminating NUL
such an array may be annotated
+with attribute nonstring
to avoid this warning. Such arrays,
+however, are not suitable arguments to functions that expect
+NUL
-terminated strings. To help detect accidental misuses of
+such arrays GCC issues warnings unless it can prove that the use is
+safe. See Common Variable Attributes.
+
]]>
+
+
-Wsubobject-linkage
Warn if a class type has a base or a field whose type uses the anonymous namespace or depends on a type with no linkage
- Warn if a class type has a base or a field whose type uses the anonymous namespace or depends
- on a type with no linkage. If a type A depends on a type B with no or internal linkage,
- defining it in multiple translation units would be an ODR violation because the meaning of B
- is different in each translation unit. If A only appears in a single translation unit, the
- best way to silence the warning is to give it internal linkage by putting it in an anonymous
- namespace as well. The compiler doesn’t give this warning for types defined in the main .C
- file, as those are unlikely to have multiple definitions.
-
- CRITICAL
-
+ Do not warn
+if a class type has a base or a field whose type uses the anonymous
+namespace or depends on a type with no linkage. If a type A depends on
+a type B with no or internal linkage, defining it in multiple
+translation units would be an ODR violation because the meaning of B
+is different in each translation unit. If A only appears in a single
+translation unit, the best way to silence the warning is to give it
+internal linkage by putting it in an anonymous namespace as well. The
+compiler doesn’t give this warning for types defined in the main .C
+file, as those are unlikely to have multiple definitions.
+-Wsubobject-linkage is enabled by default.
+]]>
+
+
+
+ -Wsuggest-attribute=cold
+ Warn about functions which might be candidates for __attribute__((cold))
+
+ Warn for cases where adding an attribute may be beneficial. The
+attributes currently supported are listed below.
+
+
+-
+
+
+
+
+
+
+
+
+
-Wsuggest-attribute=pure
¶
+-Wsuggest-attribute=const
+-Wsuggest-attribute=noreturn
+-Wmissing-noreturn
+-Wsuggest-attribute=malloc
+-Wsuggest-attribute=returns_nonnull
+-Wno-suggest-attribute=returns_nonnull
+-
+
Warn about functions that might be candidates for attributes
+pure
, const
, noreturn
, malloc
or returns_nonnull
. The compiler
+only warns for functions visible in other compilation units or (in the case of
+pure
and const
) if it cannot prove that the function returns
+normally. A function returns normally if it doesn’t contain an infinite loop or
+return abnormally by throwing, calling abort
or trapping. This analysis
+requires option -fipa-pure-const, which is enabled by default at
+-O and higher. Higher optimization levels improve the accuracy
+of the analysis.
+
+
+-
+
+
+
+
+
-Wsuggest-attribute=format
¶
+-Wmissing-format-attribute
+-
+
Warn about function pointers that might be candidates for format
+attributes. Note these are only possible candidates, not absolute ones.
+GCC guesses that function pointers with format
attributes that
+are used in assignment, initialization, parameter passing or return
+statements should have a corresponding format
attribute in the
+resulting type. I.e. the left-hand side of the assignment or
+initialization, the type of the parameter variable, or the return type
+of the containing function respectively should also have a format
+attribute to avoid the warning.
+
+GCC also warns about function definitions that might be
+candidates for format
attributes. Again, these are only
+possible candidates. GCC guesses that format
attributes
+might be appropriate for any function that calls a function like
+vprintf
or vscanf
, but this might not always be the
+case, and some functions for which format
attributes are
+appropriate may not be detected.
+
+
+-
+
-Wsuggest-attribute=cold
¶
+-
+
Warn about functions that might be candidates for cold
attribute. This
+is based on static detection and generally only warns about functions which
+always leads to a call to another cold
function such as wrappers of
+C++ throw
or fatal error reporting functions leading to abort
.
+
+
]]>
+
+
-Wsuggest-attribute=const
Warn about functions which might be candidates for __attribute__((const))
- Warn about functions which might be candidates for attribute "const". The compiler
- only warns for functions visible in other compilation units or (in the case of "pure" and "const")
- if it cannot prove that the function returns normally. A function returns normally if it doesn't
- contain an infinite loop nor returns abnormally by throwing, calling "abort()" or trapping. This
- analysis requires option -fipa-pure-const, which is enabled by default at -O and higher. Higher
- optimization levels improve the accuracy of the analysis.
-
- CRITICAL
-
+ Warn for cases where adding an attribute may be beneficial. The
+attributes currently supported are listed below.
+
+
+-
+
+
+
+
+
+
+
+
+
-Wsuggest-attribute=pure
¶
+-Wsuggest-attribute=const
+-Wsuggest-attribute=noreturn
+-Wmissing-noreturn
+-Wsuggest-attribute=malloc
+-Wsuggest-attribute=returns_nonnull
+-Wno-suggest-attribute=returns_nonnull
+-
+
Warn about functions that might be candidates for attributes
+pure
, const
, noreturn
, malloc
or returns_nonnull
. The compiler
+only warns for functions visible in other compilation units or (in the case of
+pure
and const
) if it cannot prove that the function returns
+normally. A function returns normally if it doesn’t contain an infinite loop or
+return abnormally by throwing, calling abort
or trapping. This analysis
+requires option -fipa-pure-const, which is enabled by default at
+-O and higher. Higher optimization levels improve the accuracy
+of the analysis.
+
+
+-
+
+
+
+
+
-Wsuggest-attribute=format
¶
+-Wmissing-format-attribute
+-
+
Warn about function pointers that might be candidates for format
+attributes. Note these are only possible candidates, not absolute ones.
+GCC guesses that function pointers with format
attributes that
+are used in assignment, initialization, parameter passing or return
+statements should have a corresponding format
attribute in the
+resulting type. I.e. the left-hand side of the assignment or
+initialization, the type of the parameter variable, or the return type
+of the containing function respectively should also have a format
+attribute to avoid the warning.
+
+GCC also warns about function definitions that might be
+candidates for format
attributes. Again, these are only
+possible candidates. GCC guesses that format
attributes
+might be appropriate for any function that calls a function like
+vprintf
or vscanf
, but this might not always be the
+case, and some functions for which format
attributes are
+appropriate may not be detected.
+
+
+-
+
-Wsuggest-attribute=cold
¶
+-
+
Warn about functions that might be candidates for cold
attribute. This
+is based on static detection and generally only warns about functions which
+always leads to a call to another cold
function such as wrappers of
+C++ throw
or fatal error reporting functions leading to abort
.
+
+
]]>
+
+
-Wsuggest-attribute=format
- Warn for cases where adding an attribute may be beneficial
-
- Warn for cases where adding an attribute may be beneficial. The attributes currently supported are
- listed below.
-
- -Wsuggest-attribute=pure
- -Wsuggest-attribute=const
- -Wsuggest-attribute=noreturn
-
- Warn about functions that might be candidates for attributes pure, const or noreturn. The compiler
- only warns for functions visible in other compilation units or (in the case of pure and const) if
- it cannot prove that the function returns normally. A function returns normally if it doesn’t
- contain an infinite loop or return abnormally by throwing, calling abort or trapping. This analysis
- requires option -fipa-pure-const, which is enabled by default at -O and higher. Higher optimization
- levels improve the accuracy of the analysis.
-
- -Wsuggest-attribute=format
- -Wmissing-format-attribute
-
- Warn about function pointers that might be candidates for format attributes. Note these are only
- possible candidates, not absolute ones. GCC guesses that function pointers with format attributes
- that are used in assignment, initialization, parameter passing or return statements should have a
- corresponding format attribute in the resulting type. I.e. the left-hand side of the assignment or
- initialization, the type of the parameter variable, or the return type of the containing function
- respectively should also have a format attribute to avoid the warning.
-
- GCC also warns about function definitions that might be candidates for format attributes. Again,
- these are only possible candidates. GCC guesses that format attributes might be appropriate for any
- function that calls a function like vprintf or vscanf, but this might not always be the case, and
- some functions for which format attributes are appropriate may not be detected.
-
- CRITICAL
-
+ Warn about functions which might be candidates for format attributes
+
+ Warn for cases where adding an attribute may be beneficial. The
+attributes currently supported are listed below.
+
+
+-
+
+
+
+
+
+
+
+
+
-Wsuggest-attribute=pure
¶
+-Wsuggest-attribute=const
+-Wsuggest-attribute=noreturn
+-Wmissing-noreturn
+-Wsuggest-attribute=malloc
+-Wsuggest-attribute=returns_nonnull
+-Wno-suggest-attribute=returns_nonnull
+-
+
Warn about functions that might be candidates for attributes
+pure
, const
, noreturn
, malloc
or returns_nonnull
. The compiler
+only warns for functions visible in other compilation units or (in the case of
+pure
and const
) if it cannot prove that the function returns
+normally. A function returns normally if it doesn’t contain an infinite loop or
+return abnormally by throwing, calling abort
or trapping. This analysis
+requires option -fipa-pure-const, which is enabled by default at
+-O and higher. Higher optimization levels improve the accuracy
+of the analysis.
+
+
+-
+
+
+
+
+
-Wsuggest-attribute=format
¶
+-Wmissing-format-attribute
+-
+
Warn about function pointers that might be candidates for format
+attributes. Note these are only possible candidates, not absolute ones.
+GCC guesses that function pointers with format
attributes that
+are used in assignment, initialization, parameter passing or return
+statements should have a corresponding format
attribute in the
+resulting type. I.e. the left-hand side of the assignment or
+initialization, the type of the parameter variable, or the return type
+of the containing function respectively should also have a format
+attribute to avoid the warning.
+
+GCC also warns about function definitions that might be
+candidates for format
attributes. Again, these are only
+possible candidates. GCC guesses that format
attributes
+might be appropriate for any function that calls a function like
+vprintf
or vscanf
, but this might not always be the
+case, and some functions for which format
attributes are
+appropriate may not be detected.
+
+
+-
+
-Wsuggest-attribute=cold
¶
+-
+
Warn about functions that might be candidates for cold
attribute. This
+is based on static detection and generally only warns about functions which
+always leads to a call to another cold
function such as wrappers of
+C++ throw
or fatal error reporting functions leading to abort
.
+
+
]]>
+
+
+
+ -Wsuggest-attribute=malloc
+ Warn about functions which might be candidates for __attribute__((malloc))
+
+ Warn for cases where adding an attribute may be beneficial. The
+attributes currently supported are listed below.
+
+
+-
+
+
+
+
+
+
+
+
+
-Wsuggest-attribute=pure
¶
+-Wsuggest-attribute=const
+-Wsuggest-attribute=noreturn
+-Wmissing-noreturn
+-Wsuggest-attribute=malloc
+-Wsuggest-attribute=returns_nonnull
+-Wno-suggest-attribute=returns_nonnull
+-
+
Warn about functions that might be candidates for attributes
+pure
, const
, noreturn
, malloc
or returns_nonnull
. The compiler
+only warns for functions visible in other compilation units or (in the case of
+pure
and const
) if it cannot prove that the function returns
+normally. A function returns normally if it doesn’t contain an infinite loop or
+return abnormally by throwing, calling abort
or trapping. This analysis
+requires option -fipa-pure-const, which is enabled by default at
+-O and higher. Higher optimization levels improve the accuracy
+of the analysis.
+
+
+-
+
+
+
+
+
-Wsuggest-attribute=format
¶
+-Wmissing-format-attribute
+-
+
Warn about function pointers that might be candidates for format
+attributes. Note these are only possible candidates, not absolute ones.
+GCC guesses that function pointers with format
attributes that
+are used in assignment, initialization, parameter passing or return
+statements should have a corresponding format
attribute in the
+resulting type. I.e. the left-hand side of the assignment or
+initialization, the type of the parameter variable, or the return type
+of the containing function respectively should also have a format
+attribute to avoid the warning.
+
+GCC also warns about function definitions that might be
+candidates for format
attributes. Again, these are only
+possible candidates. GCC guesses that format
attributes
+might be appropriate for any function that calls a function like
+vprintf
or vscanf
, but this might not always be the
+case, and some functions for which format
attributes are
+appropriate may not be detected.
+
+
+-
+
-Wsuggest-attribute=cold
¶
+-
+
Warn about functions that might be candidates for cold
attribute. This
+is based on static detection and generally only warns about functions which
+always leads to a call to another cold
function such as wrappers of
+C++ throw
or fatal error reporting functions leading to abort
.
+
+
]]>
+
+
-Wsuggest-attribute=noreturn
Warn about functions which might be candidates for __attribute__((noreturn))
- Warn about functions which might be candidates for attribute "noreturn". The compiler
- only warns for functions visible in other compilation units or (in the case of "pure" and "const")
- if it cannot prove that the function returns normally. A function returns normally if it doesn't
- contain an infinite loop nor returns abnormally by throwing, calling "abort()" or trapping. This
- analysis requires option -fipa-pure-const, which is enabled by default at -O and higher. Higher
- optimization levels improve the accuracy of the analysis.
-
- CRITICAL
-
+ Warn for cases where adding an attribute may be beneficial. The
+attributes currently supported are listed below.
+
+
+-
+
+
+
+
+
+
+
+
+
-Wsuggest-attribute=pure
¶
+-Wsuggest-attribute=const
+-Wsuggest-attribute=noreturn
+-Wmissing-noreturn
+-Wsuggest-attribute=malloc
+-Wsuggest-attribute=returns_nonnull
+-Wno-suggest-attribute=returns_nonnull
+-
+
Warn about functions that might be candidates for attributes
+pure
, const
, noreturn
, malloc
or returns_nonnull
. The compiler
+only warns for functions visible in other compilation units or (in the case of
+pure
and const
) if it cannot prove that the function returns
+normally. A function returns normally if it doesn’t contain an infinite loop or
+return abnormally by throwing, calling abort
or trapping. This analysis
+requires option -fipa-pure-const, which is enabled by default at
+-O and higher. Higher optimization levels improve the accuracy
+of the analysis.
+
+
+-
+
+
+
+
+
-Wsuggest-attribute=format
¶
+-Wmissing-format-attribute
+-
+
Warn about function pointers that might be candidates for format
+attributes. Note these are only possible candidates, not absolute ones.
+GCC guesses that function pointers with format
attributes that
+are used in assignment, initialization, parameter passing or return
+statements should have a corresponding format
attribute in the
+resulting type. I.e. the left-hand side of the assignment or
+initialization, the type of the parameter variable, or the return type
+of the containing function respectively should also have a format
+attribute to avoid the warning.
+
+GCC also warns about function definitions that might be
+candidates for format
attributes. Again, these are only
+possible candidates. GCC guesses that format
attributes
+might be appropriate for any function that calls a function like
+vprintf
or vscanf
, but this might not always be the
+case, and some functions for which format
attributes are
+appropriate may not be detected.
+
+
+-
+
-Wsuggest-attribute=cold
¶
+-
+
Warn about functions that might be candidates for cold
attribute. This
+is based on static detection and generally only warns about functions which
+always leads to a call to another cold
function such as wrappers of
+C++ throw
or fatal error reporting functions leading to abort
.
+
+
]]>
+
+
-Wsuggest-attribute=pure
Warn about functions which might be candidates for __attribute__((pure))
- Warn about functions which might be candidates for attribute "pure". The compiler
- only warns for functions visible in other compilation units or (in the case of "pure" and "const")
- if it cannot prove that the function returns normally. A function returns normally if it doesn't
- contain an infinite loop nor returns abnormally by throwing, calling "abort()" or trapping. This
- analysis requires option -fipa-pure-const, which is enabled by default at -O and higher. Higher
- optimization levels improve the accuracy of the analysis.
-
- CRITICAL
-
+ Warn for cases where adding an attribute may be beneficial. The
+attributes currently supported are listed below.
+
+
+-
+
+
+
+
+
+
+
+
+
-Wsuggest-attribute=pure
¶
+-Wsuggest-attribute=const
+-Wsuggest-attribute=noreturn
+-Wmissing-noreturn
+-Wsuggest-attribute=malloc
+-Wsuggest-attribute=returns_nonnull
+-Wno-suggest-attribute=returns_nonnull
+-
+
Warn about functions that might be candidates for attributes
+pure
, const
, noreturn
, malloc
or returns_nonnull
. The compiler
+only warns for functions visible in other compilation units or (in the case of
+pure
and const
) if it cannot prove that the function returns
+normally. A function returns normally if it doesn’t contain an infinite loop or
+return abnormally by throwing, calling abort
or trapping. This analysis
+requires option -fipa-pure-const, which is enabled by default at
+-O and higher. Higher optimization levels improve the accuracy
+of the analysis.
+
+
+-
+
+
+
+
+
-Wsuggest-attribute=format
¶
+-Wmissing-format-attribute
+-
+
Warn about function pointers that might be candidates for format
+attributes. Note these are only possible candidates, not absolute ones.
+GCC guesses that function pointers with format
attributes that
+are used in assignment, initialization, parameter passing or return
+statements should have a corresponding format
attribute in the
+resulting type. I.e. the left-hand side of the assignment or
+initialization, the type of the parameter variable, or the return type
+of the containing function respectively should also have a format
+attribute to avoid the warning.
+
+GCC also warns about function definitions that might be
+candidates for format
attributes. Again, these are only
+possible candidates. GCC guesses that format
attributes
+might be appropriate for any function that calls a function like
+vprintf
or vscanf
, but this might not always be the
+case, and some functions for which format
attributes are
+appropriate may not be detected.
+
+
+-
+
-Wsuggest-attribute=cold
¶
+-
+
Warn about functions that might be candidates for cold
attribute. This
+is based on static detection and generally only warns about functions which
+always leads to a call to another cold
function such as wrappers of
+C++ throw
or fatal error reporting functions leading to abort
.
+
+
]]>
+
+
+
+ -Wsuggest-attribute=returns_nonnull
+ Warn about functions which might be candidates for __attribute__((returns_nonnull))
+
+ Warn for cases where adding an attribute may be beneficial. The
+attributes currently supported are listed below.
+
+
+-
+
+
+
+
+
+
+
+
+
-Wsuggest-attribute=pure
¶
+-Wsuggest-attribute=const
+-Wsuggest-attribute=noreturn
+-Wmissing-noreturn
+-Wsuggest-attribute=malloc
+-Wsuggest-attribute=returns_nonnull
+-Wno-suggest-attribute=returns_nonnull
+-
+
Warn about functions that might be candidates for attributes
+pure
, const
, noreturn
, malloc
or returns_nonnull
. The compiler
+only warns for functions visible in other compilation units or (in the case of
+pure
and const
) if it cannot prove that the function returns
+normally. A function returns normally if it doesn’t contain an infinite loop or
+return abnormally by throwing, calling abort
or trapping. This analysis
+requires option -fipa-pure-const, which is enabled by default at
+-O and higher. Higher optimization levels improve the accuracy
+of the analysis.
+
+
+-
+
+
+
+
+
-Wsuggest-attribute=format
¶
+-Wmissing-format-attribute
+-
+
Warn about function pointers that might be candidates for format
+attributes. Note these are only possible candidates, not absolute ones.
+GCC guesses that function pointers with format
attributes that
+are used in assignment, initialization, parameter passing or return
+statements should have a corresponding format
attribute in the
+resulting type. I.e. the left-hand side of the assignment or
+initialization, the type of the parameter variable, or the return type
+of the containing function respectively should also have a format
+attribute to avoid the warning.
+
+GCC also warns about function definitions that might be
+candidates for format
attributes. Again, these are only
+possible candidates. GCC guesses that format
attributes
+might be appropriate for any function that calls a function like
+vprintf
or vscanf
, but this might not always be the
+case, and some functions for which format
attributes are
+appropriate may not be detected.
+
+
+-
+
-Wsuggest-attribute=cold
¶
+-
+
Warn about functions that might be candidates for cold
attribute. This
+is based on static detection and generally only warns about functions which
+always leads to a call to another cold
function such as wrappers of
+C++ throw
or fatal error reporting functions leading to abort
.
+
+
]]>
+
+
-Wsuggest-final-methods
- Warn about virtual methods where code quality would be improved if the method were declared with the C++11 final specifier
-
- Warn about virtual methods where code quality would be improved if the method were declared with
- the C++11 final specifier, or, if possible, its type were declared in an anonymous namespace or
- with the final specifier. This warning is more effective with link-time optimization, where the
- information about the class hierarchy graph is more complete. It is recommended to first consider
- suggestions of -Wsuggest-final-types and then rebuild with new annotations.
-
- CRITICAL
-
+ Warn about C++ virtual methods where adding final keyword would improve code quality
+
+ Warn about virtual methods where code quality would be improved if the method
+were declared with the C++11 final
specifier,
+or, if possible, its type were
+declared in an anonymous namespace or with the final
specifier.
+This warning is
+more effective with link-time optimization, where the information about the
+class hierarchy graph is more complete. It is recommended to first consider
+suggestions of -Wsuggest-final-types and then rebuild with new
+annotations.
+]]>
+
+
-Wsuggest-final-types
- Warn about types with virtual methods where code quality would be improved if the type were declared with the C++11 final specifier
-
- Warn about types with virtual methods where code quality would be improved if the type were declared
- with the C++11 final specifier, or, if possible, declared in an anonymous namespace. This allows GCC
- to more aggressively devirtualize the polymorphic calls. This warning is more effective with link
- time optimization, where the information about the class hierarchy graph is more complete.
-
- CRITICAL
-
+ Warn about C++ polymorphic types where adding final keyword would improve code quality
+
+ Warn about types with virtual methods where code quality would be improved
+if the type were declared with the C++11 final
specifier,
+or, if possible,
+declared in an anonymous namespace. This allows GCC to more aggressively
+devirtualize the polymorphic calls. This warning is more effective with
+link-time optimization,
+where the information about the class hierarchy graph is
+more complete.
+]]>
+
+
-Wsuggest-override
- Warn about overriding virtual functions that are not marked with the override keyword.
+ Suggest that the override keyword be used when the declaration of a virtual function overrides another
- Warn about overriding virtual functions that are not marked with the override keyword.
-
- CRITICAL
-
-
- -Wsurprising
- Warn about "suspicious" constructs
-
- Warn about "suspicious" constructs.
-
- CRITICAL
-
+ Warn about overriding virtual functions that are not marked with the
+override
keyword.
+]]>
+
+
-Wswitch
Warn about enumerated switches, with no default, missing a case
- Warn whenever a "switch" statement has an index of enumerated type and lacks a "case"
- for one or more of the named codes of that enumeration. (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).
-
- CRITICAL
-
+ 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-bool
- Warn whenever a switch statement has an index of boolean type and the case values are outside the range of a boolean type.
-
- Warn whenever a switch statement has an index of boolean type and the case values are outside the
- range of a boolean type. It is possible to suppress this warning by casting the controlling
- expression to a type other than bool. For example:
-
- switch ((int) (a == 4))
- {
- …
- }
-
- This warning is enabled by default for C and C++ programs.
-
- CRITICAL
-
+ Warn about switches with boolean controlling expression
+
+ Warn when a switch
statement has an index of boolean type
+and the case values are outside the range of a boolean type.
+It is possible to suppress this warning by casting the controlling
+expression to a type other than bool
. For example:
+
+
switch ((int) (a == 4))
+ {
+ …
+ }
+
+This warning is enabled by default for C and C++ programs.
+
]]>
+
+
-Wswitch-default
Warn about enumerated switches missing a "default:" statement
- Warn whenever a "switch" statement does not have a "default" case.
-
- CRITICAL
-
+ Warn whenever a switch
statement does not have a default
+case.
+]]>
+
+
-Wswitch-enum
Warn about all enumerated switches missing a specific case
- Warn whenever a "switch" statement has an index of enumerated type and lacks a "case"
- for one or more of the named codes of that enumeration. "case" labels outside the enumeration
- range also provoke warnings when this option is used. The only difference between -Wswitch and
- this option is that this option gives a warning about an omitted enumeration code even if there
- is a "default" label.
-
- CRITICAL
-
+ 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.
+]]>
+
+
+
+ -Wswitch-outside-range
+ Warn about switch values that are outside of the switch's type 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.
+]]>
+
+
-Wswitch-unreachable
- Warn whenever a switch statement contains statements between the controlling expression and the first case label, which will never be executed
-
- Warn whenever a switch statement contains statements between the controlling expression
- and the first case label, which will never be executed. For example:
-
- switch (cond)
- {
- i = 15;
- …
- case 5:
- …
- }
-
- -Wswitch-unreachable does not warn if the statement between the controlling expression
- and the first case label is just a declaration:
-
- switch (cond)
- {
- int i;
- …
- case 5:
- i = 5;
- …
- }
-
- This warning is enabled by default for C and C++ programs.
-
- CRITICAL
-
+ Warn about statements between switch's controlling expression and the first case
+
+ Warn when a switch
statement contains statements between the
+controlling expression and the first case label, which will never be
+executed. For example:
+
+
switch (cond)
+ {
+ i = 15;
+ …
+ case 5:
+ …
+ }
+
+-Wswitch-unreachable does not warn if the statement between the
+controlling expression and the first case label is just a declaration:
+
+
switch (cond)
+ {
+ int i;
+ …
+ case 5:
+ i = 5;
+ …
+ }
+
+This warning is enabled by default for C and C++ programs.
+
]]>
+
+
-Wsync-nand
Warn when __sync_fetch_and_nand and __sync_nand_and_fetch built-in functions are used
- Warn when "__sync_fetch_and_nand" and "__sync_nand_and_fetch" built-in functions are
- used. These functions changed semantics in GCC 4.4.
-
- CRITICAL
-
-
- -Wsystem-headers
- Print warning messages for constructs found in system header files
-
- Print warning messages for constructs found in system header files. Warnings from system headers
- are normally suppressed, on the assumption that they usually do not indicate real problems and
- would only make the compiler output harder to read. Using this command-line option tells GCC to
- emit warnings from system headers as if they occurred in user code. However, note that using
- -Wall in conjunction with this option does not warn about unknown pragmas in system headers—for
- that, -Wunknown-pragmas must also be used.
-
- CRITICAL
-
+ Warn when __sync_fetch_and_nand
and __sync_nand_and_fetch
+built-in functions are used. These functions changed semantics in GCC 4.4.
+]]>
+
+
+
+ -Wsynth
+ Deprecated
+
+
+
+
-Wtautological-compare
- Warn if a self-comparison always evaluates to true or false.
+ Warn if a comparison always evaluates to true or false
+
+ Warn if a self-comparison always evaluates to true or false. This
+warning detects various mistakes such as:
+
+
int i = 1;
+…
+if (i > i) { … }
+
+This warning also warns about bitwise comparisons that always evaluate
+to true or false, for instance:
+
+
if ((a & 16) == 10) { … }
+
+will always be false.
+
+This warning is enabled by -Wall.
+
]]>
+
+
+
+ -Wtemplate-id-cdtor
+ Warn about simple-template-id in a constructor or destructor
- Warn if a self-comparison always evaluates to true or false. This warning detects various mistakes
- such as:
-
- int i = 1;
- …
- if (i > i) { … }
-
- This warning is enabled by -Wall.
-
- CRITICAL
-
+ 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.
+
]]>
+
+
-Wtemplates
- Warn when a primary template declaration is encountered
-
- 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.
-
- CRITICAL
-
+ Warn on primary template declaration
+
+ 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.
+]]>
+
+
+
+ -Wterminate
+ Warn if a throw expression will always result in a call to terminate()
+
+ Disable the warning about a throw-expression that will immediately
+result in a call to terminate
.
+]]>
+
+
-Wtraditional
Warn about features not present in traditional C
-
- 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
- which 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 does not in ISO C.
- - In traditional C, some preprocessor directives did not exist. Traditional preprocessors would
- only consider 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 would ignore because the #
- does not appear as the first character on the line. It also suggests you hide directives like #pragma
- not understood by traditional C by indenting them. Some traditional implementations would not
- recognize #elif, so it suggests avoiding it altogether.
- - A function-like macro that appears without arguments.
- - The unary plus operator.
- - The U integer constant suffix, or the F or L floating point constant suffixes. (Traditional C
- does support the L suffix on integer constants.) Note, these suffixes appear in macros defined
- in the system headers of most modern systems, e.g. the _MIN/_MAX macros in "<limits.h>".
- Use of these macros in user code might normally lead to spurious warnings, however GCC's integrated
- preprocessor has enough context to avoid warning in these cases.
- - A function declared external in one block and then used after the end of the block.
- - A "switch" statement has an operand of type "long".
- - A non-"static" function declaration follows a "static" one. This construct is not accepted by
- some traditional C compilers.
- - The ISO type of an integer constant has a different width or signedness from its traditional type.
- This warning is only issued if the base of the constant is ten. I.e. hexadecimal or octal values,
- which typically represent bit patterns, are not warned about.
- - Usage of ISO string concatenation is detected.
- - Initialization of automatic aggregates.
- - Identifier conflicts with labels. Traditional C lacks a separate namespace for labels.
- - Initialization of unions. If the initializer is zero, the warning is omitted. This is done under
- the assumption that the zero initializer in user code appears conditioned on e.g. "__STDC__" to
- avoid missing initializer warnings and relies on default initialization to zero in the traditional
- C case.
- - Conversions by prototypes between fixed/floating point values and vice versa. The absence of
- these prototypes when compiling with traditional C would cause 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 will appear in your code when
- using libiberty's traditional C compatibility macros, "PARAMS" and "VPARAMS". This warning is
- also bypassed for nested functions because that feature is already a GCC extension and thus not
- relevant to traditional C compatibility.
-
-]]>
-
- CRITICAL
-
+
+ Warn about certain constructs that behave differently in traditional and
+ISO C. Also warn about ISO C constructs that have no traditional C
+equivalent, and/or problematic constructs that should be avoided.
+
+
+- Macro parameters that appear within string literals in the macro body.
+In traditional C macro replacement takes place within string literals,
+but in ISO C it does not.
+
+
- In traditional C, some preprocessor directives did not exist.
+Traditional preprocessors only considered a line to be a directive
+if the ‘#’ appeared in column 1 on the line. Therefore
+-Wtraditional warns about directives that traditional C
+understands but ignores because the ‘#’ does not appear as the
+first character on the line. It also suggests you hide directives like
+
#pragma
not understood by traditional C by indenting them. Some
+traditional implementations do not recognize #elif
, so this option
+suggests avoiding it altogether.
+
+ - A function-like macro that appears without arguments.
+
+
- The unary plus operator.
+
+
- The ‘U’ integer constant suffix, or the ‘F’ or ‘L’ floating-point
+constant suffixes. (Traditional C does support the ‘L’ suffix on integer
+constants.) Note, these suffixes appear in macros defined in the system
+headers of most modern systems, e.g. the ‘_MIN’/‘_MAX’ macros in
<limits.h>
.
+Use of these macros in user code might normally lead to spurious
+warnings, however GCC’s integrated preprocessor has enough context to
+avoid warning in these cases.
+
+ - A function declared external in one block and then used after the end of
+the block.
+
+
- A
switch
statement has an operand of type long
.
+
+ - A non-
static
function declaration follows a static
one.
+This construct is not accepted by some traditional C compilers.
+
+ - The ISO type of an integer constant has a different width or
+signedness from its traditional type. This warning is only issued if
+the base of the constant is ten. I.e. hexadecimal or octal values, which
+typically represent bit patterns, are not warned about.
+
+
- Usage of ISO string concatenation is detected.
+
+
- Initialization of automatic aggregates.
+
+
- Identifier conflicts with labels. Traditional C lacks a separate
+namespace for labels.
+
+
- Initialization of unions. If the initializer is zero, the warning is
+omitted. This is done under the assumption that the zero initializer in
+user code appears conditioned on e.g.
__STDC__
to avoid missing
+initializer warnings and relies on default initialization to zero in the
+traditional C case.
+
+ - Conversions by prototypes between fixed/floating-point values and vice
+versa. The absence of these prototypes when compiling with traditional
+C causes serious problems. This is a subset of the possible
+conversion warnings; for the full set use -Wtraditional-conversion.
+
+
- Use of ISO C style function definitions. This warning intentionally is
+not issued for prototype declarations or variadic functions
+because these ISO C features appear in your code when using
+libiberty’s traditional C compatibility macros,
PARAMS
and
+VPARAMS
. This warning is also bypassed for nested functions
+because that feature is already a GCC extension and thus not relevant to
+traditional C compatibility.
+
]]>
+
+
-Wtraditional-conversion
Warn of prototypes causing type conversions different from what would happen in the absence of prototype
- 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.
-
- CRITICAL
-
+ 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.
+]]>
+
+
-Wtrampolines
Warn whenever a trampoline is generated
- Warn about trampolines generated for pointers to nested functions.
-
- A trampoline is a small piece of data or code that is created at run time on the stack when the
- address of a nested function is taken, and is used to call the nested function indirectly. For
- some targets, it is made up of data only and thus requires no special treatment. But, for most
- targets, it is made up of code and thus requires the stack to be made executable in order for
- the program to work properly.
-
- CRITICAL
-
+ Warn about trampolines generated for pointers to nested functions.
+A trampoline is a small piece of data or code that is created at run
+time on the stack when the address of a nested function is taken, and is
+used to call the nested function indirectly. For some targets, it is
+made up of data only and thus requires no special treatment. But, for
+most targets, it is made up of code and thus requires the stack to be
+made executable in order for the program to work properly.
+]]>
+
+
-Wtrigraphs
Warn if trigraphs are encountered that might affect the meaning of the program
- Warn if any trigraphs are encountered that might change the meaning of the program
- (trigraphs within comments are not warned about).
-
- CRITICAL
-
+ 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’.
+
]]>
+
+
+
+ -Wtrivial-auto-var-init
+ Warn about cases where -ftrivial-auto-var-init cannot initialize an auto variable
+
+ Warn when -ftrivial-auto-var-init
cannot initialize the automatic
+variable. A common situation is an automatic variable that is declared
+between the controlling expression and the first case label of a switch
+statement.
+]]>
+
+
+
+ -Wtsan
+ Warn about unsupported features in ThreadSanitizer
+
+ Disable warnings about unsupported features in ThreadSanitizer.
+
+ThreadSanitizer does not support std::atomic_thread_fence
and
+can report false positives.
+
]]>
+
+
-Wtype-limits
Warn if a comparison is always true or always false due to the limited range of the data type
- Warn if a comparison is always true or always false due to the limited range of the
- data type, but do not warn for constant expressions. For example, warn if an unsigned variable
- is compared against zero with < or >=.
-
- CRITICAL
-
+ Warn if a comparison is always true or always false due to the limited
+range of the data type, but do not warn for constant expressions. For
+example, warn if an unsigned variable is compared against zero with
+<
or >=
. This warning is also enabled by
+-Wextra.
+]]>
+
+
-Wundeclared-selector
Warn about @selector()s without previously declared methods
- 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.
-
- CRITICAL
-
+ 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.
+]]>
+
+
-Wundef
Warn if an undefined macro is used in an #if directive
- Warn if an undefined identifier is evaluated in an #if directive.
-
- CRITICAL
-
+ Warn if an undefined identifier is evaluated in an #if
directive.
+Such identifiers are replaced with zero.
+]]>
+
+
- -Wunderflow
- Warn about underflow of numerical constant expressions
+ -Wunicode
+ Warn about invalid forms of delimited or named escape sequences
- Warn about underflow of numerical constant expressions
-
- CRITICAL
-
+ Don’t diagnose invalid forms of delimited or named escape sequences which are
+treated as separate tokens. Wunicode is enabled by default.
+]]>
+
+
-Wuninitialized
Warn about uninitialized automatic variables
- Warn if an automatic variable is used without first being initialized or if a variable
- may be clobbered by a "setjmp" call. In C++, warn if a non-static reference or non-static const
- member appears in a class without constructors.
-
- If you want to warn about code which uses the uninitialized value of the variable in its own
- initializer, use the -Winit-self option.
-
- These warnings occur for individual uninitialized or clobbered elements of structure, union or
- array variables as well as for variables which are uninitialized or clobbered 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 will 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.
-
- These warnings are made optional because GCC is not smart enough to see all the reasons why the
- code might be correct despite 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.
- Here is another common case:
-
- {
- int save_y;
- if (change_y) save_y = y, y = new_y;
- ...
- if (change_y) y = save_y;
- }
-
- This has no bug because "save_y" is used only if it is set.
-
- This option also warns when a non-volatile automatic variable might be changed by a call to "longjmp".
- These warnings as well are possible only in optimizing compilation.
-
- 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 which
- would cause a problem.
-
- Some spurious warnings can be avoided if you declare all the functions you use that never return as
- "noreturn".
-
- CRITICAL
-
+ Warn if an object with automatic or allocated storage duration is used
+without having been initialized. In C++, also warn if a non-static
+reference or non-static const
member appears in a class without
+constructors.
+
+In addition, passing a pointer (or in C++, a reference) to an uninitialized
+object to a const
-qualified argument of a built-in function known to
+read the object is also diagnosed by this warning.
+(-Wmaybe-uninitialized is issued for ordinary functions.)
+
+If you want to warn about code that uses the uninitialized value of the
+variable in its own initializer, use the -Winit-self option.
+
+These warnings occur for individual uninitialized elements of
+structure, union or array variables as well as for variables that are
+uninitialized as a whole. They do not occur for variables or elements
+declared volatile
. Because these warnings depend on
+optimization, the exact variables or elements for which there are
+warnings depend on the precise optimization options and version of GCC
+used.
+
+Note that there may be no warning about a variable that is used only
+to compute a value that itself is never used, because such
+computations may be deleted by data flow analysis before the warnings
+are printed.
+
+In C++, this warning also warns about using uninitialized objects in
+member-initializer-lists. For example, GCC warns about b
being
+uninitialized in the following snippet:
+
+
+
struct A {
+ int a;
+ int b;
+ A() : a(b) { }
+};
+
]]>
+
+
-Wunknown-pragmas
Warn about unrecognized pragmas
- Warn when a #pragma directive is encountered which is not understood by GCC. If this
- command line option is used, warnings will even be issued for unknown pragmas in system header
- files. This is not the case if the warnings were only enabled by the -Wall command line option.
-
- CRITICAL
-
-
- -Wunsafe-loop-optimizations
- Warn if the loop cannot be optimized due to nontrivial assumptions
-
- Warn if the loop cannot be optimized because the compiler could not assume anything
- on the bounds of the loop indices. With -funsafe-loop-optimizations warn if the compiler made such
- assumptions.
-
- CRITICAL
-
+ 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.
+]]>
+
+
-Wunsuffixed-float-constants
Warn about unsuffixed float constants
- GCC will issue a warning for any floating constant that does not have a suffix. When
- used together with -Wsystem-headers it will warn about such constants in system header files. This
- can be useful when preparing code to use with the "FLOAT_CONST_DECIMAL64" pragma from the decimal
- floating-point extension to C99.
-
- CRITICAL
-
+ Issue a warning for any floating constant that does not have
+a suffix. When used together with -Wsystem-headers it
+warns about such constants in system header files. This can be useful
+when preparing code to use with the FLOAT_CONST_DECIMAL64
pragma
+from the decimal floating-point extension to C99.
+]]>
+
+
+
+ -Wunused
+ Enable all -Wunused- warnings
+
+ All the above -Wunused options combined, except those documented
+as needing to be specified explicitly.
+
+In order to get a warning about an unused function parameter, you must
+either specify -Wextra -Wunused (note that -Wall implies
+-Wunused), or separately specify -Wunused-parameter and/or
+-Wunused-but-set-parameter.
+
+-Wunused enables only -Wunused-const-variable=1 rather than
+-Wunused-const-variable, and only for C, not C++.
+
]]>
+
+
-Wunused-but-set-parameter
Warn when a function parameter is only set, otherwise unused
- Warn whenever a function parameter is assigned to, but otherwise unused (aside from
- its declaration).
-
- To suppress this warning use the unused attribute.
-
- CRITICAL
-
+ Warn whenever a function parameter is assigned to, but otherwise unused
+(aside from its declaration).
+
+To suppress this warning use the unused
attribute
+(see Specifying Attributes of Variables).
+
+This warning is also enabled by -Wunused together with
+-Wextra.
+
]]>
+
+
-Wunused-but-set-variable
Warn when a variable is only set, otherwise unused
- Warn whenever a local variable is assigned to, but otherwise unused (aside from its
- declaration).
-
- To suppress this warning use the unused attribute.
-
- CRITICAL
-
+ 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 Specifying Attributes of Variables).
+
+This warning is also enabled by -Wunused, which is enabled
+by -Wall.
+
]]>
+
+
-Wunused-const-variable
- Warn whenever a constant static variable is unused aside from its declaration
-
- Warn whenever a constant static variable is unused aside from its declaration.
- -Wunused-const-variable=1 is enabled by -Wunused-variable for C, but not for C++.
- In C this declares variable storage, but in C++ this is not an error since const
- variables take the place of #defines.
-
- To suppress this warning use the unused attribute (see Variable Attributes).
-
- -Wunused-const-variable=1
-
- This is the warning level that is enabled by -Wunused-variable for C. It warns only
- about unused static const variables defined in the main compilation unit, but not
- about static const variables declared in any header included.
-
- -Wunused-const-variable=2
-
- This warning level also warns for unused constant static variables in headers
- (excluding system headers). This is the warning level of -Wunused-const-variable and
- must be explicitly requested since in C++ this isn’t an error and in C it might be
- harder to clean up all headers included.
-
- CRITICAL
-
-
- -Wunused-dummy-argument
- Warn about unused dummy arguments.
+ Warn when a const variable is unused
- Warn about unused dummy arguments.
-
- CRITICAL
-
+ Warn whenever a constant static variable is unused aside from its declaration.
+
+To suppress this warning use the unused
attribute
+(see Specifying Attributes of Variables).
+
+
+-Wunused-const-variable=1
+Warn about unused static const variables defined in the main
+compilation unit, but not about static const variables declared in any
+header included.
+
+-Wunused-const-variable=1 is enabled by either
+-Wunused-variable or -Wunused for C, but not for
+C++. In C this declares variable storage, but in C++ this is not an
+error since const variables take the place of #define
s.
+
+
+-Wunused-const-variable=2
+This warning level also warns for unused constant static variables in
+headers (excluding system headers). It is equivalent to the short form
+-Wunused-const-variable. This level must be explicitly
+requested in both C and C++ because it might be hard to clean up all
+headers included.
+
+
]]>
+
+
-Wunused-function
Warn when a function is unused
- Warn whenever a static function is declared but not defined or a non-inline static function is unused.
-
- CRITICAL
-
+ 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 when a label is unused
- Warn whenever a label is declared but not used.
-
- To suppress this warning use the unused attribute.
-
- CRITICAL
-
+ Warn whenever a label is declared but not used.
+This warning is enabled by -Wall.
+
+To suppress this warning use the unused
attribute
+(see Specifying Attributes of Variables).
+
]]>
+
+
-Wunused-local-typedefs
Warn when typedefs locally defined in a function are not used
- Warn when a typedef locally defined in a function is not used.
-
- CRITICAL
-
+ Warn when a typedef locally defined in a function is not used.
+This warning is enabled by -Wall.
+]]>
+
+
-Wunused-macros
Warn about macros defined in the main file that are not used
- 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 will also warn 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 CPP will
- report 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
-
- CRITICAL
-
+ 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
+
]]>
+
+
-Wunused-parameter
Warn when a function parameter is unused
- Warn whenever a function parameter is unused aside from its declaration.
-
- To suppress this warning use the unused attribute.
-
- CRITICAL
-
+ 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 Specifying Attributes of Variables).
+
]]>
+
+
-Wunused-result
Warn if a caller of a function, marked with attribute warn_unused_result, does not use its return value
- Warn if a caller of a function marked with attribute "warn_unused_result" does not
- use its return value.
-
- CRITICAL
-
+ Warn if a caller of a function marked with attribute
+warn_unused_result
(see Declaring Attributes of Functions) does not use
+its return value. The default is -Wunused-result.
+]]>
+
+
-Wunused-value
Warn when an expression value is unused
- Warn whenever a statement computes a result that is explicitly not used. To suppress
- this warning cast the unused expression to void. This includes an expression-statement or the
- left-hand side of a comma expression that contains no side effects. For example, an expression
- such as x[i,j] will cause a warning, while x[(void)i,j] will not.
-
- CRITICAL
-
+ Warn whenever a statement computes a result that is explicitly not
+used. To suppress this warning cast the unused expression to
+void
. This includes an expression-statement or the left-hand
+side of a comma expression that contains no side effects. For example,
+an expression such as x[i,j]
causes a warning, while
+x[(void)i,j]
does not.
+
+This warning is enabled by -Wall.
+
]]>
+
+
-Wunused-variable
Warn when a variable is unused
- Warn whenever a local variable or non-constant static variable is unused aside from
- its declaration.
-
- To suppress this warning use the unused attribute.
-
- CRITICAL
-
+ 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 Specifying Attributes of Variables).
+
]]>
+
+
+
+ -Wuse-after-free
+ Warn for uses of pointers to deallocated storage
+
+ Warn about uses of pointers to dynamically allocated objects that have
+been rendered indeterminate by a call to a deallocation function.
+The warning is enabled at all optimization levels but may yield different
+results with optimization than without.
+
+
+-Wuse-after-free=1
+At level 1 the warning attempts to diagnose only unconditional uses
+of pointers made indeterminate by a deallocation call or a successful
+call to realloc
, regardless of whether or not the call resulted
+in an actual reallocation of memory. This includes double-free
+calls as well as uses in arithmetic and relational expressions. Although
+undefined, uses of indeterminate pointers in equality (or inequality)
+expressions are not diagnosed at this level.
+
+-Wuse-after-free=2
+At level 2, in addition to unconditional uses, the warning also diagnoses
+conditional uses of pointers made indeterminate by a deallocation call.
+As at level 2, uses in equality (or inequality) expressions are not
+diagnosed. For example, the second call to free
in the following
+function is diagnosed at this level:
+
+
struct A { int refcount; void *data; };
+
+void release (struct A *p)
+{
+ int refcount = --p->refcount;
+ free (p);
+ if (refcount == 0)
+ free (p->data); // warning: p may be used after free
+}
+
+
+-Wuse-after-free=3
+At level 3, the warning also diagnoses uses of indeterminate pointers in
+equality expressions. All uses of indeterminate pointers are undefined
+but equality tests sometimes appear after calls to realloc
as
+an attempt to determine whether the call resulted in relocating the object
+to a different address. They are diagnosed at a separate level to aid
+gradually transitioning legacy code to safe alternatives. For example,
+the equality test in the function below is diagnosed at this level:
+
+
void adjust_pointers (int**, int);
+
+void grow (int **p, int n)
+{
+ int **q = (int**)realloc (p, n *= 2);
+ if (q == p)
+ return;
+ adjust_pointers ((int**)q, n);
+}
+
+To avoid the warning at this level, store offsets into allocated memory
+instead of pointers. This approach obviates needing to adjust the stored
+pointers after reallocation.
+
+
+-Wuse-after-free=2 is included in -Wall.
+
]]>
+
+
-Wuseless-cast
- Warn when an expression is casted to its own type
+ Warn about useless casts
- Warn when an expression is casted to its own type
-
- CRITICAL
-
+ Warn when an expression is cast to its own type. This warning does not
+occur when a class object is converted to a non-reference type as that
+is a way to create a temporary:
+
+
+
struct S { };
+void g (S&&);
+void f (S&& arg)
+{
+ g (S(arg)); // make arg prvalue so that it can bind to S&&
+}
+
]]>
+
+
-Wvarargs
- Warn upon questionable usage of the macros used to handle variable arguments like va_start
+ Warn about questionable usage of the macros used to retrieve variable arguments
- Warn upon questionable usage of the macros used to handle variable arguments like va_start.
-
- CRITICAL
-
+ Warn upon questionable usage of the macros used to handle variable
+arguments like va_start
. These warnings are enabled by default.
+]]>
+
+
-Wvariadic-macros
- Warn if variadic macros are used
+ Warn about using variadic macros
- Warn if variadic macros are used in pedantic ISO C90 mode, or the GNU alternate syntax
- when in pedantic ISO C99 mode.
-
- CRITICAL
-
+ Warn if variadic macros are used in ISO C90 mode, or if the GNU
+alternate syntax is used in ISO C99 mode. This is enabled by either
+-Wpedantic or -Wtraditional. To inhibit the warning
+messages, use -Wno-variadic-macros.
+]]>
+
+
-Wvector-operation-performance
Warn when a vector operation is compiled outside the SIMD
- Warn if vector operation is not implemented via SIMD capabilities of the architecture.
- Mainly useful for the performance tuning. Vector operation can be implemented "piecewise", which
- means that the scalar operation is performed on every vector element; "in parallel", which means
- that the vector operation is implemented using scalars of wider type, which normally is more performance
- efficient; and "as a single scalar", which means that vector fits into a scalar type.
-
- CRITICAL
-
+ Warn if vector operation is not implemented via SIMD capabilities of the
+architecture. Mainly useful for the performance tuning.
+Vector operation can be implemented piecewise
, which means that the
+scalar operation is performed on every vector element;
+in parallel
, which means that the vector operation is implemented
+using scalars of wider type, which normally is more performance efficient;
+and as a single scalar
, which means that vector fits into a
+scalar type.
+]]>
+
+
+
+ -Wvexing-parse
+ Warn about the most vexing parse syntactic ambiguity
+
+ 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.
+
]]>
+
+
-Wvirtual-inheritance
- Warn when a class is defined with a virtual direct base class
-
- Warn when a class is defined with a virtual direct base class. Some coding rules disallow multiple
- inheritance, and this may be used to enforce that rule. The warning is inactive inside a system
- header file, such as the STL, so one can still use the STL. One may also define classes that
- indirectly use virtual inheritance.
-
- CRITICAL
-
+ Warn on direct virtual inheritance
+
+ Warn when a class is defined with a virtual direct base class. Some
+coding rules disallow multiple inheritance, and this may be used to
+enforce that rule. The warning is inactive inside a system header file,
+such as the STL, so one can still use the STL. One may also define
+classes that indirectly use virtual inheritance.
+]]>
+
+
+
+ -Wvirtual-move-assign
+ Warn if a virtual base has a non-trivial move assignment operator
+
+ 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.
+]]>
+
+
-Wvla
Warn if a variable length array is used
- Warn if variable length array is used in the code.
-
- CRITICAL
-
+ Warn if a variable-length array is used in the code.
+-Wno-vla prevents the -Wpedantic warning of
+the variable-length array.
+
+This warning is upgraded to an error by -pedantic-errors.
+
]]>
+
+
-Wvla-larger-than
- Warn on uses of variable-length arrays where the size is either unbounded, or bounded by an argument that can be larger than n bytes
+ Warn on unbounded uses of variable-length arrays, and on bounded uses of variable-length arrays whose bound can be larger than <number> bytes
- If this option is used, the compiler will warn on uses of variable-length arrays
- where the size is either unbounded, or bounded by an argument that can be larger
- than n bytes. This is similar to how -Walloca-larger-than=n 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.
-
- This warning is not enabled by -Wall, and is only active when -ftree-vrp is active
- (default for -O2 and above).
-
- See also -Walloca-larger-than=n.
-
- CRITICAL
-
+ 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.
+
]]>
+
+
+
+ -Wvla-parameter
+ Warn about mismatched declarations of VLA parameters
+
+ Warn about redeclarations of functions involving arguments of Variable
+Length Array types of inconsistent kinds or forms, and enable the detection
+of out-of-bounds accesses to such parameters by warnings such as
+-Warray-bounds.
+
+If the first function declaration uses the VLA form the bound specified
+in the array is assumed to be the minimum number of elements expected to
+be provided in calls to the function and the maximum number of elements
+accessed by it. Failing to provide arguments of sufficient size or
+accessing more than the maximum number of elements may be diagnosed.
+
+For example, the warning triggers for the following redeclarations because
+the first one allows an array of any size to be passed to f
while
+the second one specifies that the array argument must have at least n
+elements. In addition, calling f
with the associated VLA bound
+parameter in excess of the actual VLA bound triggers a warning as well.
+
+
+
void f (int n, int[n]);
+// warning: argument 2 previously declared as a VLA
+void f (int, int[]);
+
+void g (int n)
+{
+ if (n > 4)
+ return;
+ int a[n];
+ // warning: access to a by f may be out of bounds
+ f (sizeof a, a);
+ …
+}
+
+
+-Wvla-parameter is included in -Wall. The
+-Warray-parameter option triggers warnings for similar problems
+involving ordinary array arguments.
+
]]>
+
+
+
+ -Wvolatile
+ Warn about deprecated uses of volatile qualifier
+
+ Warn about deprecated uses of the volatile
qualifier. This includes
+postfix and prefix ++
and --
expressions of
+volatile
-qualified types, using simple assignments where the left
+operand is a volatile
-qualified non-class type for their value,
+compound assignments where the left operand is a volatile
-qualified
+non-class type, volatile
-qualified function return type,
+volatile
-qualified parameter type, and structured bindings of a
+volatile
-qualified type. This usage was deprecated in C++20.
+
+Enabled by default with -std=c++20.
+
]]>
+
+
-Wvolatile-register-var
Warn when a register variable is declared volatile
- Warn if a register variable is declared volatile. The volatile modifier does not
- inhibit all optimizations that may eliminate reads and/or writes to register variables.
-
- CRITICAL
-
+ Warn if a register variable is declared volatile. The volatile
+modifier does not inhibit all optimizations that may eliminate reads
+and/or writes to register variables. This warning is enabled by
+-Wall.
+]]>
+
+
-Wwrite-strings
- Warn about deprecated conversion from string literals to 'char *'.
-
- When compiling C, give string constants the type "const char[length]" so that copying
- the address of one into a non-"const" "char *" pointer will get a warning. These warnings will
- 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 will
- just be 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.
-
- CRITICAL
-
+ In C++, nonzero means warn about deprecated conversion from string literals to 'char *'. In C, similar warning, except that the conversion is of course not deprecated by the ISO C standard
+
+ 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.
+
]]>
+
+
+
+ -Wxor-used-as-pow
+ Warn about xor operators where it appears the user meant exponentiation
+
+ Disable warnings about uses of ^
, the exclusive or operator,
+where it appears the code meant exponentiation.
+Specifically, the warning occurs when the
+left-hand side is the decimal constant 2 or 10 and the right-hand side
+is also a decimal constant.
+
+In C and C++, ^
means exclusive or, whereas in some other languages
+(e.g. TeX and some versions of BASIC) it means exponentiation.
+
+This warning can be silenced by converting one of the operands to
+hexadecimal as well as by compiling with -Wno-xor-used-as-pow.
+
]]>
+
+
-Wzero-as-null-pointer-constant
Warn when a literal '0' is used as null pointer
- Warn when a literal '0' is used as null pointer
-
- CRITICAL
-
-
+ Warn when a literal ‘0’ is used as null pointer constant. This can
+be useful to facilitate the conversion to nullptr
in C++11.
+]]>
+
+
+
+ -Wzero-length-bounds
+ Warn about accesses to interior zero-length array members
+
+ Warn about accesses to elements of zero-length array members that might
+overlap other members of the same object. Declaring interior zero-length
+arrays is discouraged because accesses to them are undefined.
+See Arrays of Length Zero.
+
+For example, the first two stores in function bad
are diagnosed
+because the array elements overlap the subsequent members b
and
+c
. The third store is diagnosed by -Warray-bounds
+because it is beyond the bounds of the enclosing object.
+
+
+
struct X { int a[0]; int b, c; };
+struct X x;
+
+void bad (void)
+{
+ x.a[0] = 0; // -Wzero-length-bounds
+ x.a[1] = 1; // -Wzero-length-bounds
+ x.a[2] = 2; // -Warray-bounds
+}
+
+Option -Wzero-length-bounds is enabled by -Warray-bounds.
+
]]>
+
+
+
+ -Whsa
+ Warn when a function cannot be expanded to HSAIL
+
+ Issue a warning when HSAIL cannot be emitted for the compiled function or OpenMP construct.]]>
+
+
+
+ -Wmudflap
+ Warn about constructs not instrumented by -fmudflap
+
+ -fmudflap]]>
+
+
+
+ -Wunsafe-loop-optimizations
+ Warn if the loop cannot be optimized due to nontrivial assumptions
+
+ Warn if the loop cannot be optimized because the compiler cannot assume anything on the bounds of the loop indices. With -funsafe-loop-optimizations warn if the compiler makes such assumptions.]]>
+
+
+
diff --git a/cxx-sensors/src/test/java/org/sonar/cxx/sensors/compiler/gcc/CxxCompilerGccRuleRepositoryTest.java b/cxx-sensors/src/test/java/org/sonar/cxx/sensors/compiler/gcc/CxxCompilerGccRuleRepositoryTest.java
index 5354d63bb..658e04006 100644
--- a/cxx-sensors/src/test/java/org/sonar/cxx/sensors/compiler/gcc/CxxCompilerGccRuleRepositoryTest.java
+++ b/cxx-sensors/src/test/java/org/sonar/cxx/sensors/compiler/gcc/CxxCompilerGccRuleRepositoryTest.java
@@ -38,7 +38,7 @@ void createGccRulesTest() {
def.define(context);
RulesDefinition.Repository repo = context.repository(CxxCompilerGccRuleRepository.KEY);
- assertThat(repo.rules()).hasSize(231);
+ assertThat(repo.rules()).hasSize(378);
}
}
diff --git a/cxx-sensors/src/tools/gcc_createrules.py b/cxx-sensors/src/tools/gcc_createrules.py
new file mode 100755
index 000000000..5a7fab972
--- /dev/null
+++ b/cxx-sensors/src/tools/gcc_createrules.py
@@ -0,0 +1,321 @@
+#!/usr/bin/env python3
+
+# -*- coding: utf-8 -*-
+# SonarQube C++ Community Plugin (cxx plugin)
+# Copyright (C) 2024 SonarOpenCommunity
+# http://github.com/SonarOpenCommunity/sonar-cxx
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 3 of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with this program; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+"""Python script to read the GCC warnings from the internet."""
+
+import re
+import sys
+import textwrap
+import urllib.request
+
+from bs4 import BeautifulSoup
+
+from utils_createrules import CDATA
+from utils_createrules import write_rules_xml
+from utils_createrules import get_cdata_capable_xml_etree
+
+
+GCC_VERSION = "14.2.0"
+
+old_warnings = {'-Whsa':
+ {
+ 'name': 'Warn when a function cannot be expanded to HSAIL',
+ 'description': 'Issue a warning when HSAIL cannot be emitted for the compiled function or OpenMP construct.
'
+ },
+ '-Wmudflap':
+ {
+ 'name': 'Warn about constructs not instrumented by -fmudflap',
+ 'description': 'Suppress warnings about constructs that cannot be instrumented by -fmudflap'
+ },
+ '-Wunsafe-loop-optimizations':
+ {
+ 'name': 'Warn if the loop cannot be optimized due to nontrivial assumptions',
+ 'description': 'Warn if the loop cannot be optimized because the compiler cannot assume anything on the bounds of the loop indices. With -funsafe-loop-optimizations warn if the compiler makes such assumptions.
'
+ }
+ }
+
+
+et = get_cdata_capable_xml_etree()
+
+
+def add_template_rules(rules):
+ """Add template rule(s) to XML."""
+
+ rule_key = '=CustomRuleTemplate'
+ rule_name = 'Rule template for GCC custom rules'
+ # pylint: disable=line-too-long
+ rule_description = textwrap.dedent("""
+
+ Follow these steps to make your custom rules available in SonarQube:
+
+
+
+ - Create a new rule in SonarQube by "copying" this rule template and specify the
CheckId
of your custom rule, a title, a description, and a default severity.
+ - Enable the newly created rule in your quality profile
+
+ - Relaunch an analysis on your projects, et voilà, your custom rules are executed!
+
"""
+ )
+
+ rule = et.Element('rule')
+ et.SubElement(rule, 'key').text = rule_key
+ et.SubElement(rule, 'cardinality').text = "MULTIPLE"
+ et.SubElement(rule, 'name').text=rule_name
+ et.SubElement(rule, 'description').append(CDATA(rule_description))
+ rules.append(rule)
+
+
+def add_unknown_rule(rules):
+ """Add unknown rule to XML."""
+ rule_key = 'unknown'
+ rule_name = 'Unknown GCC rule'
+ rule_description = textwrap.dedent("""
+
+ By activating this rule, unknown rules in the reports are not discarded but mapped to this rule. This helps to identify unknown rules, e.g. from newer versions of a tool.
+
+ """
+ )
+ rule_severity = 'INFO'
+
+ rule = et.Element('rule')
+ et.SubElement(rule, 'key').text = rule_key
+ et.SubElement(rule, 'name').text=rule_name
+ et.SubElement(rule, 'description').append(CDATA(rule_description))
+ et.SubElement(rule, 'severity').text = rule_severity
+ rules.append(rule)
+
+
+def add_default_rule(rules):
+ """Add default rule to XML."""
+ rule_key = 'default'
+ rule_name = 'Default compiler warnings'
+ rule_description = 'Default compiler warnings.'
+
+ rule = et.Element('rule')
+ et.SubElement(rule, 'key').text = rule_key
+ et.SubElement(rule, 'name').text=rule_name
+ et.SubElement(rule, 'description').text = rule_description
+ rules.append(rule)
+
+
+def create_rules(warnings, rules):
+ """Add warnings as rules to XML."""
+ for key, data in list(warnings.items()):
+ rule = et.Element('rule')
+
+ name = data['name']
+ if ' ' in name and key != '-Wwrite-strings':
+ # After ' ' too much information appears, except for 'Wwrite-strings'
+ name = name.split(' ')[0]
+ name = name.removesuffix('.').replace('\\"', '"')
+
+ et.SubElement(rule, 'key').text = key
+ et.SubElement(rule, 'name').text = name
+ if 'description' in data:
+ cdata = CDATA(data['description'])
+ else:
+ cdata = CDATA(name)
+ et.SubElement(rule, 'description').append(cdata)
+
+ rules.append(rule)
+
+
+def read_warning_html_description(url):
+ """Read warning description from provided url."""
+
+ with urllib.request.urlopen(url) as fp:
+ #with open("Warning-Options.html") as fp:
+ soup = BeautifulSoup(fp, 'html.parser')
+
+ warnings = {}
+
+ second_entry_warnings_found = {'-Wimplicit-fallthrough': False, '-Wstrict-aliasing': False}
+
+ for dl in soup.body.div.find_all("dl", recursive=False):
+ found_warning_name = False
+ warning_name = ''
+ for child in dl.children:
+ if not found_warning_name and child.name == "dt":
+ warning_name = child.get_text().strip().split(" ", 1)[0]
+
+ if not warning_name.startswith("-W") or warning_name == '-Wall':
+ continue
+
+ if warning_name.startswith("-Wno-"):
+ warning_name = warning_name[:2] + warning_name[5:]
+ elif warning_name == "-Wnopacked-bitfield-compat":
+ # This is both misspelled in the docs, and never used in the diagnostics, which use "note" instead of "warning" anyway
+ # (i.e. the message is "::: note: offset of packed bit-field '’ has changed in GCC 4.4")
+ # But it's already there, let's keep it.
+ warning_name = "-Wpacked-bitfield-compat"
+ warning_name = warning_name.split('=', 1)[0]
+
+ # When a warning is listed twice, usually the first entry has better documentation
+ # Some (e.g. -Wendif-labels) are simply duplicated
+ if warning_name in warnings.keys():
+ continue
+
+ if warning_name in second_entry_warnings_found:
+ if not second_entry_warnings_found[warning_name]:
+ second_entry_warnings_found[warning_name] = True
+ continue
+
+ found_warning_name = True
+ elif found_warning_name and child.name == "dd":
+ description = str(child)[4:-6] # There is a better way of removing the ?
+ # Remove class attributes from tags
+ description = re.sub(r' class="[^"]+"', '', description)
+
+ swappable_prefix = 'Do not warn '
+ if description.startswith(swappable_prefix):
+ description = f'
Warn {description.removeprefix(swappable_prefix)}'
+
+ if warning_name == '-Wsuggest-attribute':
+ for attribute in ['pure', 'const', 'noreturn', 'format', 'cold','malloc','returns_nonnull']:
+ warnings[f"-Wsuggest-attribute={attribute}"] = {'description': description}
+ found_warning_name = False
+ continue
+
+ # -Wextra mainly enables other warnings, but it's also a warning on its own.
+ # Let's include only the relevant part of the documentation.
+ if warning_name == '-Wextra':
+ description = re.sub(r'.*\n', '', description, flags=re.DOTALL)
+
+ warnings[warning_name] = {'description': description}
+
+ found_warning_name = False
+
+ return warnings
+
+
+def read_warning_html_descriptions():
+ """Collect warning HTML descriptions into a single dictionary"""
+ urls = [
+ f"https://gcc.gnu.org/onlinedocs/gcc-{GCC_VERSION}/gcc/C_002b_002b-Dialect-Options.html",
+ f"https://gcc.gnu.org/onlinedocs/gcc-{GCC_VERSION}/gcc/Warning-Options.html",
+ f"https://gcc.gnu.org/onlinedocs/gcc-{GCC_VERSION}/gcc/Static-Analyzer-Options.html",
+ f"https://gcc.gnu.org/onlinedocs/gcc-{GCC_VERSION}/gcc/Objective-C-and-Objective-C_002b_002b-Dialect-Options.html"
+ ]
+
+ warnings = {}
+ for url in urls:
+ warnings |= read_warning_html_description(url)
+
+ return warnings
+
+
+def read_warning_options():
+ """Read warnings from HTML pages.
+
+ - root pages are defined in 'urls'
+ """
+
+ warnings = {}
+
+ field = 0
+ warning_name = ''
+ urls = [
+ f'https://gcc.gnu.org/git/?p=gcc.git;a=blob_plain;f=gcc/common.opt;hb=refs/tags/releases/gcc-{GCC_VERSION}',
+ f'https://gcc.gnu.org/git/?p=gcc.git;a=blob_plain;f=gcc/c-family/c.opt;hb=refs/tags/releases/gcc-{GCC_VERSION}',
+ f'https://gcc.gnu.org/git/?p=gcc.git;a=blob_plain;f=gcc/analyzer/analyzer.opt;hb=refs/tags/releases/gcc-{GCC_VERSION}',
+ f'https://gcc.gnu.org/git/?p=gcc.git;a=blob_plain;f=gcc/config/i386/mingw.opt;hb=refs/tags/releases/gcc-{GCC_VERSION}'
+ ]
+ for url in urls:
+ with urllib.request.urlopen(url) as file:
+ found_option = False
+ found_warning = False
+ for line in file:
+ line = line.decode('utf-8')
+ # AFAIK the format is not documented. The parsing logic comes from "gcc/opt-gather.awk" in the gcc repo.
+ if re.match(r'^[ \t]*(;|$)', line):
+ found_option = False
+ found_warning = False
+ field = 0
+ warning_name = ''
+ elif re.match(r'^[^ \t]', line):
+ if not found_option:
+ warning_name = line.strip()
+ if warning_name == 'Waligned-new=':
+ # 'Waligned-new' has a better 'name'
+ continue
+ if warning_name.startswith("Wno-"):
+ warning_name = 'W' + warning_name[4:]
+ if not warning_name.startswith('Wsuggest-attribute'):
+ # The -Wsuggest-attribute=XXX warnings actually appear as such in the compiler output
+ warning_name = warning_name.split('=', 1)[0]
+ found_option = True
+ if warning_name[0] == 'W' and warning_name != 'Wall' and warning_name != 'Wsystem-headers' and f'-{warning_name}' not in warnings:
+ found_warning = True
+ elif found_warning:
+ field = field + 1
+ name = line.strip()
+ if field == 1:
+ tags = name.split(' ')
+ # aligned-new good 'name' is listed under 'Waligned-new', but only in 'Waligned-new=' is tagged as a warning
+ if warning_name != 'Waligned-new' and ('Warning' not in tags or 'Ignore' in tags or any(item.startswith('Alias(') for item in tags)):
+ found_warning = False
+ elif field == 2:
+ if '\t' in name:
+ # Some 'names' first include a "usage" description, followed by a "meaning" description. We only want the meaning.
+ warnings[f'-{warning_name}'] = {'name': name.split('\t', 1)[1]}
+ else:
+ if name == 'Do not warn about using \\"long long\\" when -pedantic.':
+ name = 'Warn about using "long long"'
+ warnings[f'-{warning_name}'] = {'name': name}
+ else:
+ warnings[f'-{warning_name}']['name'] += ' ' + name
+ else:
+ assert(False)
+
+ return warnings
+
+def read_warnings():
+ warnings = read_warning_options()
+ html_warnings = read_warning_html_descriptions()
+
+ for key in warnings:
+ if key in html_warnings:
+ warnings[key]['description'] = html_warnings[key]['description']
+
+ return dict(sorted(list(warnings.items())))
+
+def create_xml(warnings):
+ """Write rules in XML format to stdout."""
+ rules = et.Element('rules')
+
+ add_template_rules(rules)
+ add_unknown_rule(rules)
+ add_default_rule(rules)
+ create_rules(warnings, rules)
+
+ write_rules_xml(rules, sys.stdout)
+
+
+def main():
+ """Main."""
+ warnings = read_warnings()
+ warnings |= old_warnings
+ create_xml(warnings)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
From 0c7b6c307393de5b08c02b16fe6cc93e465a000c Mon Sep 17 00:00:00 2001
From: Cristian Morales Vega
Date: Fri, 22 Nov 2024 11:55:49 +0000
Subject: [PATCH 2/2] gcc sensor: Improve performance
I have not actually measured, but regexs are slow.
---
.../sonar/cxx/sensors/compiler/gcc/CxxCompilerGccSensor.java | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/cxx-sensors/src/main/java/org/sonar/cxx/sensors/compiler/gcc/CxxCompilerGccSensor.java b/cxx-sensors/src/main/java/org/sonar/cxx/sensors/compiler/gcc/CxxCompilerGccSensor.java
index e47a6a9f3..efd0f5fc3 100644
--- a/cxx-sensors/src/main/java/org/sonar/cxx/sensors/compiler/gcc/CxxCompilerGccSensor.java
+++ b/cxx-sensors/src/main/java/org/sonar/cxx/sensors/compiler/gcc/CxxCompilerGccSensor.java
@@ -115,7 +115,9 @@ protected String alignId(@Nullable String id) {
if (id == null || "".equals(id)) {
id = DEFAULT_ID;
}
- id = id.replaceAll("=$", "");
+ if (id.charAt(id.length() - 1) == '=') {
+ id = id.substring(0, id.length() - 1);
+ }
switch(id) {
case "-Wc++0x-compat":