5.7.5 Options for Controlling Warnings and Errors

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

You can request many specific warnings with options beginning -W; for example, -Wimplicit, to request warnings on implicit declarations. Each of these specific warning options also has a negative form beginning -Wno- to turn off warnings; for example, -Wno-implicit. This manual lists only one of the two forms, whichever is not the default.

The options shown in the tables below are the more commonly used warning options that control messages issued by the compile. In the (linked) sections that follow, the options that affect warnings generally are discussed.

Table 5-12. Warning and Error Options Implied by All Warnings
Option

(links to explanatory section)

Definition
-fsyntax-onlyCheck the code for syntax, but don’t do anything beyond that.
-pedanticIssue all the warnings demanded by strict ANSI C. Reject all programs that use forbidden extensions.
-pedantic-errorsLike -pedantic, except that errors are produced rather than warnings.
-wInhibit all warning messages.
-WallEnable all warnings about constructions that some users consider questionable, and that are easy to avoid, even in conjunction with macros.
-WaddressWarn 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 indicates 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.
-Warray-boundsWhen combined with -02 or greater, warns for many instances out-of-bounds array indices and pointer offsets. This feature cannot detect all cases. Enabled with -Wall command.
-Wchar-subscriptsWarn if an array subscript has type char.

-Wcomment

Warn whenever a comment-start sequence /* appears in a /*comment, or whenever a Backslash-Newline appears in a // comment.
-Wdiv-by-zeroWarn about compile-time integer division by zero. To inhibit the warning messages, use -Wno-div-by-zero. Floating-point division by zero is not warned about, as it can be a -legitimate way of obtaining infinities and NaNs.

This is the default.

-WformatCheck calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified.
-Wformat-smart-io=level A level of 1 disables warnings thrown by Smart IO to indicate anomalies in IO function format strings. A level of 0 enables these warnings.
-WimplicitEquivalent to specifying both -Wimplicit-int and -Wimplicit-function-declaration.
-Wimplicit-function- declarationGive a warning whenever a function is used before being declared.
-Wimplicit-intWarn when a declaration does not specify a type.
-WmainWarn if the type of main is suspicious. main should be a function with external linkage, returning int, taking either zero, two, or three arguments of appropriate types.
-Wmissing-bracesWarn 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 } };

-Wmultistatement-macrosWarns for unsafe macro expansion as a body of a statement such as if, else, while, switch, or for. Enabled with -Wall command.
-Wno-multicharWarn if a multi-character character constant is used. Usually, such constants are typographical errors. Since they have implementation-defined values, they should not be used in portable code. The following example illustrates the use of a multi-character character constant:

char

xx(void)

{

return('xx');

}

-WparenthesesWarn 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 find confusing.
-Wreturn-typeWarn 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.
-Wsequence-pointWarn about code that may have undefined semantics because of violations of sequence point rules in the C standard.

The C standard defines the order in which expressions in a 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. 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 has 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 standard specifies 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.

-Wsizeof-pointer-divWarns for suspicious divisions of the size of a pointer by the size of the elements it points to, which looks like the usual way to compute the array size but won't work out correctly with pointers.
-WswitchWarn whenever a switch statement has an index of enumeral 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.
-Wsystem-headersPrint 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 the compiler 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.
-WtrigraphsWarn if any trigraphs are encountered (assuming they are enabled).
-WuninitializedWarn if an automatic variable is used without first being initialized.

These warnings are possible only when optimization is enabled, because they require data flow information that is computed only when optimizing.

These warnings occur only for variables that are candidates for register allocation. Therefore, they do not occur for a variable that is declared volatile, or whose address is taken, or whose size is other than 1, 2, 4 or 8 bytes. Also, they do not occur for structures, unions or arrays, even when they are in registers.

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.

-Wunknown-pragmasWarn when a #pragma directive is encountered which is not understood by the compiler. 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.
-WunusedWarn whenever a variable is unused aside from its declaration, whenever a function is declared static but never defined, whenever a label is declared but not used, and whenever a statement computes a result that is explicitly not used.

In order to get a warning about an unused function parameter, both -W and -Wunused must be specified.

Casting an expression to void suppresses this warning for an expression. Similarly, the unused attribute suppresses this warning for unused variables, parameters and labels.

-Wunused-functionWarn whenever a static function is declared but not defined or a non-inline static function is unused.
-Wunused-labelWarn whenever a label is declared but not used. To suppress this warning, use the unused attribute.
-Wunused-parameterWarn whenever a function parameter is unused aside from its declaration. To suppress this warning, use the unused attribute.
-Wunused-variableWarn whenever a local variable or non-constant static variable is unused aside from its declaration. To suppress this warning, use the unused attribute.
-Wunused-valueWarn whenever a statement computes a result that is explicitly not used. To suppress this warning, cast the expression to void.

The following -W options are not implied by -Wall. Some of them warn about constructions that users generally do not consider questionable, but which you might occasionally wish to check for. Others warn about constructions that are necessary or hard to avoid in some cases, and there is no simple way to modify the code to suppress the warning.

Table 5-13. Warning And Error Options Not Implied By All Warnings
OptionDefinition

-Wextra

(formerly) -W

Enable extra warning flags that are not enabled by -Wall.
-Waggregate-returnWarn if any functions that return structures or unions are defined or called.
-Wbad-function-castWarn whenever a function call is cast to a non-matching type. For example, warn if int foof() is cast to anything *.
-Wcast-alignWarn 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 *.
-Wcast-qualWarn 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 *.
-WconversionWarn 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.

Also, warn if a negative integer constant expression is implicitly converted to an unsigned type. For example, warn about the assignment x = -1 if x is unsigned. But do not warn about explicit casts like (unsigned) -1.

-WerrorMake all warnings into errors.
-WinlineWarn if a function can not be inlined, and either it was declared as inline, or else the -finline-functions option was given.
-Wlarger-than-lenWarn whenever an object of larger than len bytes is defined.
-Wlong-long

-Wno-long-long

Warn if long long type is used. This is default. To inhibit the warning messages, use -Wno-long-long. Flags -Wlong-long and -Wno-long-long are taken into account only when -pedantic flag is used.
-Wmissing-declarationsWarn if a global function is defined without a previous declaration. Do so even if the definition itself provides a prototype.
-Wmissing-
format-attributeIf -Wformat is enabled, also warn about functions that might be candidates for format attributes. Note these are only possible candidates, not absolute ones. This option has no effect unless -Wformat is enabled.
-Wmissing-noreturnWarn about functions that might be candidates for attribute noreturn. These are only possible candidates, not absolute ones. Care should be taken to manually verify functions. In fact, do not ever return before adding the noreturn attribute, otherwise subtle code generation bugs could be introduced.
-Wmissing-prototypesWarn if a global function is defined without a previous prototype declaration. This warning is issued even if the definition itself provides a prototype. This option can be used to detect global functions that are not declared in header files.
-Wnested-externsWarn if an extern declaration is encountered within a function.
-Wno-deprecated-
declarationsDo not warn about uses of functions, variables and types marked as deprecated by using the deprecated attribute.
-WpaddedWarn if padding is included in a structure, either to align an element of the structure or to align the whole structure.
-Wpointer-arithWarn about anything that depends on the size of a function type or of void. The compiler assigns these types a size of 1, for convenience in calculations with void * pointers and pointers to functions.
-Wredundant-declsWarn if anything is declared more than once in the same scope, even in cases where multiple declaration is valid and changes nothing.
-WshadowWarn whenever a local variable shadows another local variable.
-Wsign-compare

-Wno-sign-compare

Warn when a comparison between signed and unsigned values could produce an incorrect result when the signed value is converted to unsigned. This warning is also enabled by -W. To get the other warnings of -W without this warning, use -W -Wno-sign-compare.
-Wstrict-prototypesWarn 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 which specifies the argument types).
-WtraditionalWarn about certain constructs that behave differently in traditional and ANSI C.
  • Macro arguments occurring within string constants in the macro body. These would substitute the argument in traditional C, but are part of the constant in ANSI C.
  • 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 nonstatic function declaration follows a static one. This construct is not accepted by some traditional C compilers.
-WundefWarn if an undefined identifier is evaluated in an #if directive.
-Wunreachable-codeWarn if the compiler detects that code will never be executed.

It is possible for this option to produce a warning even though there are circumstances under which part of the affected line can be executed, so care should be taken when removing apparently unreachable code. For instance, when a function is inlined, a warning may mean that the line is unreachable in only one inlined copy of the function.

-Wwrite-stringsGive string constants the type const char[length] so that copying the address of one into a non-const char * pointer gets a warning. At compile time, these warnings help you find code that you 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’s just a nuisance, which is why -Wall does not request these warnings.