GCC
Section: GNU (1)Updated: 2012-03-05
Index Return to Main Contents
NAME
gcc - GNU project C and C++ compilerSYNOPSIS
gcc [-c|-S|-E] [-std=standard][-g] [-pg] [-Olevel]
[-Wwarn...] [-pedantic]
[-Idir...] [-Ldir...]
[-Dmacro[=defn]...] [-Umacro]
[-foption...] [-mmachine-option...]
[-o outfile] [@file] infile...
Only the most useful options are listed here; see below for the remainder. g++ accepts mostly the same options as gcc.
DESCRIPTION
When you invoke GCC, it normally does preprocessing, compilation, assembly and linking. The ``overall options'' allow you to stop this process at an intermediate stage. For example, the -c option says not to run the linker. Then the output consists of object files output by the assembler.Other options are passed on to one stage of processing. Some options control the preprocessor and others the compiler itself. Yet other options control the assembler and linker; most of these are not documented here, since you rarely need to use any of them.
Most of the command line options that you can use with GCC are useful for C programs; when an option is only useful with another language (usually C++), the explanation says so explicitly. If the description for a particular option does not mention a source language, you can use that option with all supported languages.
The gcc program accepts options and file names as operands. Many options have multi-letter names; therefore multiple single-letter options may not be grouped: -dv is very different from -d -v.
You can mix options and other arguments. For the most part, the order you use doesn't matter. Order does matter when you use several options of the same kind; for example, if you specify -L more than once, the directories are searched in the order specified. Also, the placement of the -l option is significant.
Many options have long names starting with -f or with -W---for example, -fmove-loop-invariants, -Wformat and so on. Most of these have both positive and negative forms; the negative form of -ffoo would be -fno-foo. This manual documents only one of these two forms, whichever one is not the default.
OPTIONS
Option Summary
Here is a summary of all the options, grouped by type. Explanations are in the following sections.-

Xstormy16 Options -msim
Xtensa Options -mconst16 -mno-const16 -mfused-madd -mno-fused-madd -mserialize-volatile -mno-serialize-volatile -mtext-section-literals -mno-text-section-literals -mtarget-align -mno-target-align -mlongcalls -mno-longcalls
zSeries Options See S/390 and zSeries Options.
- Code Generation Options
- -fcall-saved-reg -fcall-used-reg -ffixed-reg -fexceptions -fnon-call-exceptions -funwind-tables -fasynchronous-unwind-tables -finhibit-size-directive -finstrument-functions -finstrument-functions-exclude-function-list=sym,sym,... -finstrument-functions-exclude-file-list=file,file,... -fno-common -fno-ident -fpcc-struct-return -fpic -fPIC -fpie -fPIE -fno-jump-tables -frecord-gcc-switches -freg-struct-return -fshort-enums -fshort-double -fshort-wchar -fverbose-asm -fpack-struct[=n] -fstack-check -fstack-limit-register=reg -fstack-limit-symbol=sym -fno-stack-limit -fargument-alias -fargument-noalias -fargument-noalias-global -fargument-noalias-anything -fleading-underscore -ftls-model=model -ftrapv -fwrapv -fbounds-check -fvisibility
Options Controlling the Kind of Output
Compilation can involve up to four stages: preprocessing, compilation proper, assembly and linking, always in that order. GCC is capable of preprocessing and compiling several files either into several assembler input files, or into one assembler input file; then each assembler input file produces an object file, and linking combines all the object files (those newly compiled, and those specified as input) into an executable file.For any given input file, the file name suffix determines what kind of compilation is done:
- file.c
- C source code which must be preprocessed.
- file.i
- C source code which should not be preprocessed.
- file.ii
- C++ source code which should not be preprocessed.
- file.m
- Objective-C source code. Note that you must link with the libobjc library to make an Objective-C program work.
- file.mi
- Objective-C source code which should not be preprocessed.
- file.mm
- file.M
- Objective-C++ source code. Note that you must link with the libobjc library to make an Objective-C++ program work. Note that .M refers to a literal capital M.
- file.mii
- Objective-C++ source code which should not be preprocessed.
- file.h
- C, C++, Objective-C or Objective-C++ header file to be turned into a precompiled header.
- file.cc
- file.cp
- file.cxx
- file.cpp
- file.CPP
- file.c++
- file.C
- C++ source code which must be preprocessed. Note that in .cxx, the last two letters must both be literally x. Likewise, .C refers to a literal capital C.
- file.mm
- file.M
- Objective-C++ source code which must be preprocessed.
- file.mii
- Objective-C++ source code which should not be preprocessed.
- file.hh
- file.H
- file.hp
- file.hxx
- file.hpp
- file.HPP
- file.h++
- file.tcc
- C++ header file to be turned into a precompiled header.
- file.f
- file.for
- file.ftn
- Fixed form Fortran source code which should not be preprocessed.
- file.F
- file.FOR
- file.fpp
- file.FPP
- file.FTN
- Fixed form Fortran source code which must be preprocessed (with the traditional preprocessor).
- file.f90
- file.f95
- file.f03
- file.f08
- Free form Fortran source code which should not be preprocessed.
- file.F90
- file.F95
- file.F03
- file.F08
- Free form Fortran source code which must be preprocessed (with the traditional preprocessor).
- file.ads
- Ada source code file which contains a library unit declaration (a declaration of a package, subprogram, or generic, or a generic instantiation), or a library unit renaming declaration (a package, generic, or subprogram renaming declaration). Such files are also called specs.
- file.adb
- Ada source code file containing a library unit body (a subprogram or package body). Such files are also called bodies.
- file.s
- Assembler code.
- file.S
- file.sx
- Assembler code which must be preprocessed.
- other
- An object file to be fed straight into linking. Any file name with no recognized suffix is treated this way.
You can specify the input language explicitly with the -x option:
- -x language
-
Specify explicitly the language for the following input files
(rather than letting the compiler choose a default based on the file
name suffix). This option applies to all following input files until
the next -x option. Possible values for language are:
c c-header c-cpp-output c++ c++-header c++-cpp-output objective-c objective-c-header objective-c-cpp-output objective-c++ objective-c++-header objective-c++-cpp-output assembler assembler-with-cpp ada f77 f77-cpp-input f95 f95-cpp-input java
- -x none
- Turn off any specification of a language, so that subsequent files are handled according to their file name suffixes (as they are if -x has not been used at all).
- -pass-exit-codes
- Normally the gcc program will exit with the code of 1 if any phase of the compiler returns a non-success return code. If you specify -pass-exit-codes, the gcc program will instead return with numerically highest error produced by any phase that returned an error indication. The C, C++, and Fortran frontends return 4, if an internal compiler error is encountered.
If you only want some of the stages of compilation, you can use -x (or filename suffixes) to tell gcc where to start, and one of the options -c, -S, or -E to say where gcc is to stop. Note that some combinations (for example, -x cpp-output -E) instruct gcc to do nothing at all.
- -c
-
Compile or assemble the source files, but do not link. The linking
stage simply is not done. The ultimate output is in the form of an
object file for each source file.
By default, the object file name for a source file is made by replacing the suffix .c, .i, .s, etc., with .o.
Unrecognized input files, not requiring compilation or assembly, are ignored.
- -S
-
Stop after the stage of compilation proper; do not assemble. The output
is in the form of an assembler code file for each non-assembler input
file specified.
By default, the assembler file name for a source file is made by replacing the suffix .c, .i, etc., with .s.
Input files that don't require compilation are ignored.
- -E
-
Stop after the preprocessing stage; do not run the compiler proper. The
output is in the form of preprocessed source code, which is sent to the
standard output.
Input files which don't require preprocessing are ignored.
- -o file
-
Place output in file file. This applies regardless to whatever
sort of output is being produced, whether it be an executable file,
an object file, an assembler file or preprocessed C code.
If -o is not specified, the default is to put an executable file in a.out, the object file for source.suffix in source.o, its assembler file in source.s, a precompiled header file in source.suffix.gch, and all preprocessed C source on standard output.
- -v
- Print (on standard error output) the commands executed to run the stages of compilation. Also print the version number of the compiler driver program and of the preprocessor and the compiler proper.
- -###
- Like -v except the commands are not executed and all command arguments are quoted. This is useful for shell scripts to capture the driver-generated command lines.
- -pipe
- Use pipes rather than temporary files for communication between the various stages of compilation. This fails to work on some systems where the assembler is unable to read from a pipe; but the GNU assembler has no trouble.
- -combine
- If you are compiling multiple source files, this option tells the driver to pass all the source files to the compiler at once (for those languages for which the compiler can handle this). This will allow intermodule analysis (IMA) to be performed by the compiler. Currently the only language for which this is supported is C. If you pass source files for multiple languages to the driver, using this option, the driver will invoke the compiler(s) that support IMA once each, passing each compiler all the source files appropriate for it. For those languages that do not support IMA this option will be ignored, and the compiler will be invoked once for each source file in that language. If you use this option in conjunction with -save-temps, the compiler will generate multiple pre-processed files (one for each source file), but only one (combined) .o or .s file.
- --help
- Print (on the standard output) a description of the command line options understood by gcc. If the -v option is also specified then --help will also be passed on to the various processes invoked by gcc, so that they can display the command line options they accept. If the -Wextra option has also been specified (prior to the --help option), then command line options which have no documentation associated with them will also be displayed.
- --target-help
- Print (on the standard output) a description of target-specific command line options for each tool. For some targets extra target-specific information may also be printed.
- --help={class|[^]qualifier}[,...]
-
Print (on the standard output) a description of the command line
options understood by the compiler that fit into all specified classes
and qualifiers. These are the supported classes:
-
- optimizers
- This will display all of the optimization options supported by the compiler.
- warnings
- This will display all of the options controlling warning messages produced by the compiler.
- target
- This will display target-specific options. Unlike the --target-help option however, target-specific options of the linker and assembler will not be displayed. This is because those tools do not currently support the extended --help= syntax.
- params
- This will display the values recognized by the --param option.
- language
- This will display the options supported for language, where language is the name of one of the languages supported in this version of GCC.
- common
- This will display the options that are common to all languages.
-
These are the supported qualifiers:
- undocumented
- Display only those options which are undocumented.
- joined
- Display options which take an argument that appears after an equal sign in the same continuous piece of text, such as: --help=target.
- separate
- Display options which take an argument that appears as a separate word following the original option, such as: -o output-file.
-
Thus for example to display all the undocumented target-specific switches supported by the compiler the following can be used:
--help=target,undocumented
The sense of a qualifier can be inverted by prefixing it with the ^ character, so for example to display all binary warning options (i.e., ones that are either on or off and that do not take an argument), which have a description the following can be used:
--help=warnings,^joined,^undocumented
The argument to --help= should not consist solely of inverted qualifiers.
Combining several classes is possible, although this usually restricts the output by so much that there is nothing to display. One case where it does work however is when one of the classes is target. So for example to display all the target-specific optimization options the following can be used:
--help=target,optimizers
The --help= option can be repeated on the command line. Each successive use will display its requested class of options, skipping those that have already been displayed.
If the -Q option appears on the command line before the --help= option, then the descriptive text displayed by --help= is changed. Instead of describing the displayed options, an indication is given as to whether the option is enabled, disabled or set to a specific value (assuming that the compiler knows this at the point where the --help= option is used).
Here is a truncated example from the ARM port of gcc:
% gcc -Q -mabi=2 --help=target -c The following options are target specific: -mabi= 2 -mabort-on-noreturn [disabled] -mapcs [disabled]
The output is sensitive to the effects of previous command line options, so for example it is possible to find out which optimizations are enabled at -O2 by using:
-Q -O2 --help=optimizers
Alternatively you can discover which binary optimizations are enabled by -O3 by using:
gcc -c -Q -O3 --help=optimizers > /tmp/O3-opts gcc -c -Q -O2 --help=optimizers > /tmp/O2-opts diff /tmp/O2-opts /tmp/O3-opts | grep enabled
-
- --version
- Display the version number and copyrights of the invoked GCC.
- -wrapper
-
Invoke all subcommands under a wrapper program. It takes a single
comma separated list as an argument, which will be used to invoke
the wrapper:
gcc -c t.c -wrapper gdb,--args
This will invoke all subprograms of gcc under ``gdb --args'', thus cc1 invocation will be ``gdb --args cc1 ...''.
- @file
-
Read command-line options from file. The options read are
inserted in place of the original @file option. If file
does not exist, or cannot be read, then the option will be treated
literally, and not removed.
Options in file are separated by whitespace. A whitespace character may be included in an option by surrounding the entire option in either single or double quotes. Any character (including a backslash) may be included by prefixing the character to be included with a backslash. The file may itself contain additional @file options; any such options will be processed recursively.
Compiling C++ Programs
C++ source files conventionally use one of the suffixes .C, .cc, .cpp, .CPP, .c++, .cp, or .cxx; C++ header files often use .hh, .hpp, .H, or (for shared template code) .tcc; and preprocessed C++ files use the suffix .ii. GCC recognizes files with these names and compiles them as C++ programs even if you call the compiler the same way as for compiling C programs (usually with the name gcc).However, the use of gcc does not add the C++ library. g++ is a program that calls GCC and treats .c, .h and .i files as C++ source files instead of C source files unless -x is used, and automatically specifies linking against the C++ library. This program is also useful when precompiling a C header file with a .h extension for use in C++ compilations. On many systems, g++ is also installed with the name c++.
When you compile C++ programs, you may specify many of the same command-line options that you use for compiling programs in any language; or command-line options meaningful for C and related languages; or options that are meaningful only for C++ programs.
Options Controlling C Dialect
The following options control the dialect of C (or languages derived from C, such as C++, Objective-C and Objective-C++) that the compiler accepts:- -ansi
-
In C mode, this is equivalent to -std=c89. In C++ mode, it is
equivalent to -std=c++98.
This turns off certain features of GCC that are incompatible with ISO C90 (when compiling C code), or of standard C++ (when compiling C++ code), such as the "asm" and "typeof" keywords, and predefined macros such as "unix" and "vax" that identify the type of system you are using. It also enables the undesirable and rarely used ISO trigraph feature. For the C compiler, it disables recognition of C++ style // comments as well as the "inline" keyword.
The alternate keywords "__asm__", "__extension__", "__inline__" and "__typeof__" continue to work despite -ansi. You would not want to use them in an ISO C program, of course, but it is useful to put them in header files that might be included in compilations done with -ansi. Alternate predefined macros such as "__unix__" and "__vax__" are also available, with or without -ansi.
The -ansi option does not cause non-ISO programs to be rejected gratuitously. For that, -pedantic is required in addition to -ansi.
The macro "__STRICT_ANSI__" is predefined when the -ansi option is used. Some header files may notice this macro and refrain from declaring certain functions or defining certain macros that the ISO standard doesn't call for; this is to avoid interfering with any programs that might use these names for other things.
Functions that would normally be built in but do not have semantics defined by ISO C (such as "alloca" and "ffs") are not built-in functions when -ansi is used.
- -std=
-
Determine the language standard. This option
is currently only supported when compiling C or C++.
The compiler can accept several base standards, such as c89 or c++98, and GNU dialects of those standards, such as gnu89 or gnu++98. By specifying a base standard, the compiler will accept all programs following that standard and those using GNU extensions that do not contradict it. For example, -std=c89 turns off certain features of GCC that are incompatible with ISO C90, such as the "asm" and "typeof" keywords, but not other GNU extensions that do not have a meaning in ISO C90, such as omitting the middle term of a "?:" expression. On the other hand, by specifying a GNU dialect of a standard, all features the compiler support are enabled, even when those features change the meaning of the base standard and some strict-conforming programs may be rejected. The particular standard is used by -pedantic to identify which features are GNU extensions given that version of the standard. For example -std=gnu89 -pedantic would warn about C++ style // comments, while -std=gnu99 -pedantic would not.
A value for this option must be provided; possible values are
-
- c89
- iso9899:1990
- Support all ISO C90 programs (certain GNU extensions that conflict with ISO C90 are disabled). Same as -ansi for C code.
- iso9899:199409
- ISO C90 as modified in amendment 1.
- c99
- c9x
- iso9899:1999
- iso9899:199x
- ISO C99. Note that this standard is not yet fully supported; see <http://gcc.gnu.org/gcc-4.4/c99status.html> for more information. The names c9x and iso9899:199x are deprecated.
- gnu89
- GNU dialect of ISO C90 (including some C99 features). This is the default for C code.
- gnu99
- gnu9x
- GNU dialect of ISO C99. When ISO C99 is fully implemented in GCC, this will become the default. The name gnu9x is deprecated.
- c++98
- The 1998 ISO C++ standard plus amendments. Same as -ansi for C++ code.
- gnu++98
- GNU dialect of -std=c++98. This is the default for C++ code.
- c++0x
- The working draft of the upcoming ISO C++0x standard. This option enables experimental features that are likely to be included in C++0x. The working draft is constantly changing, and any feature that is enabled by this flag may be removed from future versions of GCC if it is not part of the C++0x standard.
- gnu++0x
- GNU dialect of -std=c++0x. This option enables experimental features that may be removed in future versions of GCC.
-
- -fgnu89-inline
-
The option -fgnu89-inline tells GCC to use the traditional
GNU semantics for "inline" functions when in C99 mode.
This option is accepted and ignored by GCC versions 4.1.3 up to but not including 4.3. In GCC versions 4.3 and later it changes the behavior of GCC in C99 mode. Using this option is roughly equivalent to adding the "gnu_inline" function attribute to all inline functions.The option -fno-gnu89-inline explicitly tells GCC to use the C99 semantics for "inline" when in C99 or gnu99 mode (i.e., it specifies the default behavior). This option was first supported in GCC 4.3. This option is not supported in C89 or gnu89 mode.
The preprocessor macros "__GNUC_GNU_INLINE__" and "__GNUC_STDC_INLINE__" may be used to check which semantics are in effect for "inline" functions.
- -aux-info filename
-
Output to the given filename prototyped declarations for all functions
declared and/or defined in a translation unit, including those in header
files. This option is silently ignored in any language other than C.
Besides declarations, the file indicates, in comments, the origin of each declaration (source file and line), whether the declaration was implicit, prototyped or unprototyped (I, N for new or O for old, respectively, in the first character after the line number and the colon), and whether it came from a declaration or a definition (C or F, respectively, in the following character). In the case of function definitions, a K&R-style list of arguments followed by their declarations is also provided, inside comments, after the declaration.
- -fno-asm
-
Do not recognize "asm", "inline" or "typeof" as a
keyword, so that code can use these words as identifiers. You can use
the keywords "__asm__", "__inline__" and "__typeof__"
instead. -ansi implies -fno-asm.
In C++, this switch only affects the "typeof" keyword, since "asm" and "inline" are standard keywords. You may want to use the -fno-gnu-keywords flag instead, which has the same effect. In C99 mode (-std=c99 or -std=gnu99), this switch only affects the "asm" and "typeof" keywords, since "inline" is a standard keyword in ISO C99.
- -fno-builtin
- -fno-builtin-function
-
Don't recognize built-in functions that do not begin with
__builtin_ as prefix.
GCC normally generates special code to handle certain built-in functions more efficiently; for instance, calls to "alloca" may become single instructions that adjust the stack directly, and calls to "memcpy" may become inline copy loops. The resulting code is often both smaller and faster, but since the function calls no longer appear as such, you cannot set a breakpoint on those calls, nor can you change the behavior of the functions by linking with a different library. In addition, when a function is recognized as a built-in function, GCC may use information about that function to warn about problems with calls to that function, or to generate more efficient code, even if the resulting code still contains calls to that function. For example, warnings are given with -Wformat for bad calls to "printf", when "printf" is built in, and "strlen" is known not to modify global memory.
With the -fno-builtin-function option only the built-in function function is disabled. function must not begin with __builtin_. If a function is named that is not built-in in this version of GCC, this option is ignored. There is no corresponding -fbuiltin-function option; if you wish to enable built-in functions selectively when using -fno-builtin or -ffreestanding, you may define macros such as:
#define abs(n) __builtin_abs ((n)) #define strcpy(d, s) __builtin_strcpy ((d), (s))
- -fhosted
- Assert that compilation takes place in a hosted environment. This implies -fbuiltin. A hosted environment is one in which the entire standard library is available, and in which "main" has a return type of "int". Examples are nearly everything except a kernel. This is equivalent to -fno-freestanding.
- -ffreestanding
- Assert that compilation takes place in a freestanding environment. This implies -fno-builtin. A freestanding environment is one in which the standard library may not exist, and program startup may not necessarily be at "main". The most obvious example is an OS kernel. This is equivalent to -fno-hosted.
- -fopenmp
- Enable handling of OpenMP directives "#pragma omp" in C/C++ and "!$omp" in Fortran. When -fopenmp is specified, the compiler generates parallel code according to the OpenMP Application Program Interface v2.5 <http://www.openmp.org/>. This option implies -pthread, and thus is only supported on targets that have support for -pthread.
- -fms-extensions
-
Accept some non-standard constructs used in Microsoft header files.
Some cases of unnamed fields in structures and unions are only accepted with this option.
- -trigraphs
- Support ISO C trigraphs. The -ansi option (and -std options for strict ISO C conformance) implies -trigraphs.
- -no-integrated-cpp
-
Performs a compilation in two passes: preprocessing and compiling. This
option allows a user supplied ``cc1'', ``cc1plus'', or ``cc1obj'' via the
-B option. The user supplied compilation step can then add in
an additional preprocessing step after normal preprocessing but before
compiling. The default is to use the integrated cpp (internal cpp)
The semantics of this option will change if ``cc1'', ``cc1plus'', and ``cc1obj'' are merged.
- -traditional
- -traditional-cpp
- Formerly, these options caused GCC to attempt to emulate a pre-standard C compiler. They are now only supported with the -E switch. The preprocessor continues to support a pre-standard mode. See the GNU CPP manual for details.
- -fcond-mismatch
- Allow conditional expressions with mismatched types in the second and third arguments. The value of such an expression is void. This option is not supported for C++.
- -flax-vector-conversions
- Allow implicit conversions between vectors with differing numbers of elements and/or incompatible element types. This option should not be used for new code.
- -funsigned-char
-
Let the type "char" be unsigned, like "unsigned char".
Each kind of machine has a default for what "char" should be. It is either like "unsigned char" by default or like "signed char" by default.
Ideally, a portable program should always use "signed char" or "unsigned char" when it depends on the signedness of an object. But many programs have been written to use plain "char" and expect it to be signed, or expect it to be unsigned, depending on the machines they were written for. This option, and its inverse, let you make such a program work with the opposite default.
The type "char" is always a distinct type from each of "signed char" or "unsigned char", even though its behavior is always just like one of those two.
- -fsigned-char
-
Let the type "char" be signed, like "signed char".
Note that this is equivalent to -fno-unsigned-char, which is the negative form of -funsigned-char. Likewise, the option -fno-signed-char is equivalent to -funsigned-char.
- -fsigned-bitfields
- -funsigned-bitfields
- -fno-signed-bitfields
- -fno-unsigned-bitfields
- These options control whether a bit-field is signed or unsigned, when the declaration does not use either "signed" or "unsigned". By default, such a bit-field is signed, because this is consistent: the basic integer types such as "int" are signed types.
Options Controlling C++ Dialect
This section describes the command-line options that are only meaningful for C++ programs; but you can also use most of the GNU compiler options regardless of what language your program is in. For example, you might compile a file "firstClass.C" like this:
g++ -g -frepo -O -c firstClass.C
In this example, only -frepo is an option meant only for C++ programs; you can use the other options with any language supported by GCC.
Here is a list of options that are only for compiling C++ programs:
- -fabi-version=n
-
Use version n of the C++ ABI. Version 2 is the version of the
C++ ABI that first appeared in G++ 3.4. Version 1 is the version of
the C++ ABI that first appeared in G++ 3.2. Version 0 will always be
the version that conforms most closely to the C++ ABI specification.
Therefore, the ABI obtained using version 0 will change as ABI bugs
are fixed.
The default is version 2.
- -fno-access-control
- Turn off all access checking. This switch is mainly useful for working around bugs in the access control code.
- -fcheck-new
- Check that the pointer returned by "operator new" is non-null before attempting to modify the storage allocated. This check is normally unnecessary because the C++ standard specifies that "operator new" will only return 0 if it is declared throw(), in which case the compiler will always check the return value even without this option. In all other cases, when "operator new" has a non-empty exception specification, memory exhaustion is signalled by throwing "std::bad_alloc". See also new (nothrow).
- -fconserve-space
-
Put uninitialized or runtime-initialized global variables into the
common segment, as C does. This saves space in the executable at the
cost of not diagnosing duplicate definitions. If you compile with this
flag and your program mysteriously crashes after "main()" has
completed, you may have an object that is being destroyed twice because
two definitions were merged.
This option is no longer useful on most targets, now that support has been added for putting variables into BSS without making them common.
- -fno-deduce-init-list
-
Disable deduction of a template type parameter as
std::initializer_list from a brace-enclosed initializer list, i.e.
template <class T> auto forward(T t) -> decltype (realfn (t)) { return realfn (t); } void f() { forward({1,2}); // call forward<std::initializer_list<int>> }
This option is present because this deduction is an extension to the current specification in the C++0x working draft, and there was some concern about potential overload resolution problems.
- -ffriend-injection
-
Inject friend functions into the enclosing namespace, so that they are
visible outside the scope of the class in which they are declared.
Friend functions were documented to work this way in the old Annotated
C++ Reference Manual, and versions of G++ before 4.1 always worked
that way. However, in ISO C++ a friend function which is not declared
in an enclosing scope can only be found using argument dependent
lookup. This option causes friends to be injected as they were in
earlier releases.
This option is for compatibility, and may be removed in a future release of G++.
- -fno-elide-constructors
- The C++ standard allows an implementation to omit creating a temporary which is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases.
- -fno-enforce-eh-specs
- Don't generate code to check for violation of exception specifications at runtime. This option violates the C++ standard, but may be useful for reducing code size in production builds, much like defining NDEBUG. This does not give user code permission to throw exceptions in violation of the exception specifications; the compiler will still optimize based on the specifications, so throwing an unexpected exception will result in undefined behavior.
- -ffor-scope
- -fno-for-scope
-
If -ffor-scope is specified, the scope of variables declared in
a for-init-statement is limited to the for loop itself,
as specified by the C++ standard.
If -fno-for-scope is specified, the scope of variables declared in
a for-init-statement extends to the end of the enclosing scope,
as was the case in old versions of G++, and other (traditional)
implementations of C++.
The default if neither flag is given to follow the standard, but to allow and give a warning for old-style code that would otherwise be invalid, or have different behavior.
- -fno-gnu-keywords
- Do not recognize "typeof" as a keyword, so that code can use this word as an identifier. You can use the keyword "__typeof__" instead. -ansi implies -fno-gnu-keywords.
- -fno-implicit-templates
- Never emit code for non-inline templates which are instantiated implicitly (i.e. by use); only emit code for explicit instantiations.
- -fno-implicit-inline-templates
- Don't emit code for implicit instantiations of inline templates, either. The default is to handle inlines differently so that compiles with and without optimization will need the same set of explicit instantiations.
- -fno-implement-inlines
- To save space, do not emit out-of-line copies of inline functions controlled by #pragma implementation. This will cause linker errors if these functions are not inlined everywhere they are called.
- -fms-extensions
- Disable pedantic warnings about constructs used in MFC, such as implicit int and getting a pointer to member function via non-standard syntax.
- -fno-nonansi-builtins
- Disable built-in declarations of functions that are not mandated by ANSI/ISO C. These include "ffs", "alloca", "_exit", "index", "bzero", "conjf", and other related functions.
- -fno-operator-names
- Do not treat the operator name keywords "and", "bitand", "bitor", "compl", "not", "or" and "xor" as synonyms as keywords.
- -fno-optional-diags
- Disable diagnostics that the standard says a compiler does not need to issue. Currently, the only such diagnostic issued by G++ is the one for a name having multiple meanings within a class.
- -fpermissive
- Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using -fpermissive will allow some nonconforming code to compile.
- -frepo
- Enable automatic template instantiation at link time. This option also implies -fno-implicit-templates.
- -fno-rtti
- Disable generation of information about every class with virtual functions for use by the C++ runtime type identification features (dynamic_cast and typeid). If you don't use those parts of the language, you can save some space by using this flag. Note that exception handling uses the same information, but it will generate it as needed. The dynamic_cast operator can still be used for casts that do not require runtime type information, i.e. casts to "void *" or to unambiguous base classes.
- -fstats
- Emit statistics about front-end processing at the end of the compilation. This information is generally only useful to the G++ development team.
- -ftemplate-depth-n
- Set the maximum instantiation depth for template classes to n. A limit on the template instantiation depth is needed to detect endless recursions during template class instantiation. ANSI/ISO C++ conforming programs must not rely on a maximum depth greater than 17.
- -fno-threadsafe-statics
- Do not emit the extra code to use the routines specified in the C++ ABI for thread-safe initialization of local statics. You can use this option to reduce code size slightly in code that doesn't need to be thread-safe.
- -fuse-cxa-atexit
- Register destructors for objects with static storage duration with the "__cxa_atexit" function rather than the "atexit" function. This option is required for fully standards-compliant handling of static destructors, but will only work if your C library supports "__cxa_atexit".
- -fno-use-cxa-get-exception-ptr
- Don't use the "__cxa_get_exception_ptr" runtime routine. This will cause "std::uncaught_exception" to be incorrect, but is necessary if the runtime routine is not available.
- -fvisibility-inlines-hidden
-
This switch declares that the user does not attempt to compare
pointers to inline methods where the addresses of the two functions
were taken in different shared objects.
The effect of this is that GCC may, effectively, mark inline methods with "__attribute__ ((visibility ("hidden")))" so that they do not appear in the export table of a DSO and do not require a PLT indirection when used within the DSO. Enabling this option can have a dramatic effect on load and link times of a DSO as it massively reduces the size of the dynamic export table when the library makes heavy use of templates.
The behavior of this switch is not quite the same as marking the methods as hidden directly, because it does not affect static variables local to the function or cause the compiler to deduce that the function is defined in only one shared object.
You may mark a method as having a visibility explicitly to negate the effect of the switch for that method. For example, if you do want to compare pointers to a particular inline method, you might mark it as having default visibility. Marking the enclosing class with explicit visibility will have no effect.
Explicitly instantiated inline methods are unaffected by this option as their linkage might otherwise cross a shared library boundary.
- -fvisibility-ms-compat
-
This flag attempts to use visibility settings to make GCC's C++
linkage model compatible with that of Microsoft Visual Studio.
The flag makes these changes to GCC's linkage model:
-
- 1.
- It sets the default visibility to "hidden", like -fvisibility=hidden.
- 2.
- Types, but not their members, are not hidden by default.
- 3.
- The One Definition Rule is relaxed for types without explicit visibility specifications which are defined in more than one different shared object: those declarations are permitted if they would have been permitted when this option was not used.
-
In new code it is better to use -fvisibility=hidden and export those classes which are intended to be externally visible. Unfortunately it is possible for code to rely, perhaps accidentally, on the Visual Studio behavior.
Among the consequences of these changes are that static data members of the same type with the same name but defined in different shared objects will be different, so changing one will not change the other; and that pointers to function members defined in different shared objects may not compare equal. When this flag is given, it is a violation of the ODR to define types with the same name differently.
-
- -fno-weak
- Do not use weak symbol support, even if it is provided by the linker. By default, G++ will use weak symbols if they are available. This option exists only for testing, and should not be used by end-users; it will result in inferior code and has no benefits. This option may be removed in a future release of G++.
- -nostdinc++
- Do not search for header files in the standard directories specific to C++, but do still search the other standard directories. (This option is used when building the C++ library.)
In addition, these optimization, warning, and code generation options have meanings only for C++ programs:
- -fno-default-inline
-
Do not assume inline for functions defined inside a class scope.
Note that these functions will have linkage like inline functions; they just won't be inlined by default. - -Wabi (C, Objective-C, C++ and Objective-C++ only)
-
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.
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.
The known incompatibilities at this point include:
-
- *
-
Incorrect handling of tail-padding for bit-fields. G++ may attempt to
pack data into the same byte as a base class. For example:
struct A { virtual void f(); int f1 : 1; }; struct B : public A { int f2 : 1; };
In this case, G++ will place "B::f2" into the same byte as"A::f1"; other compilers will not. You can avoid this problem by explicitly padding "A" so that its size is a multiple of the byte size on your platform; that will cause G++ and other compilers to layout "B" identically.
- *
-
Incorrect handling of tail-padding for virtual bases. G++ does not use
tail padding when laying out virtual bases. For example:
struct A { virtual void f(); char c1; }; struct B { B(); char c2; }; struct C : public A, public virtual B {};
In this case, G++ will not place "B" into the tail-padding for "A"; other compilers will. You can avoid this problem by explicitly padding "A" so that its size is a multiple of its alignment (ignoring virtual base classes); that will cause G++ and other compilers to layout "C" identically.
- *
-
Incorrect handling of bit-fields with declared widths greater than that
of their underlying types, when the bit-fields appear in a union. For
example:
union U { int i : 4096; };
Assuming that an "int" does not have 4096 bits, G++ will make the union too small by the number of bits in an "int".
- *
-
Empty classes can be placed at incorrect offsets. For example:
struct A {}; struct B { A a; virtual void f (); }; struct C : public B, public A {};
G++ will place the "A" base class of "C" at a nonzero offset; it should be placed at offset zero. G++ mistakenly believes that the "A" data member of "B" is already at offset zero.
- *
-
Names of template functions whose types involve "typename" or
template template parameters can be mangled incorrectly.
template <typename Q> void f(typename Q::X) {} template <template <typename> class Q> void f(typename Q<int>::X) {}
Instantiations of these templates may be mangled incorrectly.
-
It also warns psABI related changes. The known psABI changes at this point include:
- *
-
For SYSV/x86-64, when passing union with long double, it is changed to
pass in memory as specified in psABI. For example:
union U { long double ld; int i; };
"union U" will always be passed in memory.
-
- -Wctor-dtor-privacy (C++ and Objective-C++ only)
- 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.
- -Wnon-virtual-dtor (C++ and Objective-C++ only)
- 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. This warning is also enabled if -Weffc++ is specified.
- -Wreorder (C++ and Objective-C++ only)
-
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. This warning is enabled by -Wall.
The following -W... options are not affected by -Wall.
- -Weffc++ (C++ and Objective-C++ only)
-
Warn about violations of the following style guidelines from Scott Meyers'
Effective C++ 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 ",".
-
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.
-
- -Wstrict-null-sentinel (C++ and Objective-C++ only)
- 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.
- -Wno-non-template-friend (C++ and Objective-C++ only)
- 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.
- -Wold-style-cast (C++ and Objective-C++ only)
- 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.
- -Woverloaded-virtual (C++ and Objective-C++ only)
-
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.
- -Wno-pmf-conversions (C++ and Objective-C++ only)
- Disable the diagnostic for converting a bound pointer to member function to a plain pointer.
- -Wsign-promo (C++ and Objective-C++ only)
-
Warn when overload resolution chooses a promotion from unsigned or
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 =.
Options Controlling Objective-C and Objective-C++ Dialects
(NOTE: This manual does not describe the Objective-C and Objective-C++ languages themselves. SeeThis section describes the command-line options that are only meaningful for Objective-C and Objective-C++ programs, but you can also use most of the language-independent GNU compiler options. For example, you might compile a file "some_class.m" like this:
gcc -g -fgnu-runtime -O -c some_class.m
In this example, -fgnu-runtime is an option meant only for Objective-C and Objective-C++ programs; you can use the other options with any language supported by GCC.
Note that since Objective-C is an extension of the C language, Objective-C compilations may also use options specific to the C front-end (e.g., -Wtraditional). Similarly, Objective-C++ compilations may use C++-specific options (e.g., -Wabi).
Here is a list of options that are only for compiling Objective-C and Objective-C++ programs:
- -fconstant-string-class=class-name
- Use class-name as the name of the class to instantiate for each literal string specified with the syntax<EMAIL_ADDRESS>The default class name is "NXConstantString" if the GNU runtime is being used, and "NSConstantString" if the NeXT runtime is being used (see below). The -fconstant-cfstrings option, if also present, will override the -fconstant-string-class setting and cause<EMAIL_ADDRESS>literals to be laid out as constant CoreFoundation strings.
- -fgnu-runtime
- Generate object code compatible with the standard GNU Objective-C runtime. This is the default for most types of systems.
- -fnext-runtime
- Generate output compatible with the NeXT runtime. This is the default for NeXT-based systems, including Darwin and Mac OS X. The macro "__NEXT_RUNTIME__" is predefined if (and only if) this option is used.
- -fno-nil-receivers
- Assume that all Objective-C message dispatches (e.g., "[receiver message:arg]") in this translation unit ensure that the receiver is not "nil". This allows for more efficient entry points in the runtime to be used. Currently, this option is only available in conjunction with the NeXT runtime on Mac OS X 10.3 and later.
- -fobjc-call-cxx-cdtors
-
For each Objective-C class, check if any of its instance variables is a
C++ object with a non-trivial default constructor. If so, synthesize a
special "- (id) .cxx_construct" instance method that will run
non-trivial default constructors on any such instance variables, in order,
and then return "self". Similarly, check if any instance variable
is a C++ object with a non-trivial destructor, and if so, synthesize a
special "- (void) .cxx_destruct" method that will run
all such default destructors, in reverse order.
The "- (id) .cxx_construct" and/or "- (void) .cxx_destruct" methods thusly generated will only operate on instance variables declared in the current Objective-C class, and not those inherited from superclasses. It is the responsibility of the Objective-C runtime to invoke all such methods in an object's inheritance hierarchy. The "- (id) .cxx_construct" methods will be invoked by the runtime immediately after a new object instance is allocated; the "- (void) .cxx_destruct" methods will be invoked immediately before the runtime deallocates an object instance.
As of this writing, only the NeXT runtime on Mac OS X 10.4 and later has support for invoking the "- (id) .cxx_construct" and "- (void) .cxx_destruct" methods.
- -fobjc-direct-dispatch
- Allow fast jumps to the message dispatcher. On Darwin this is accomplished via the comm page.
- -fobjc-exceptions
-
Enable syntactic support for structured exception handling in Objective-C,
similar to what is offered by C++ and Java. This option is
unavailable in conjunction with the NeXT runtime on Mac OS X 10.2 and
earlier.
@try { ... @throw expr; ... } @catch (AnObjCClass *exc) { ... @throw expr; ... @throw; ... } @catch (AnotherClass *exc) { ... } @catch (id allOthers) { ... } @finally { ... @throw expr; ... }
The @throw statement may appear anywhere in an Objective-C or Objective-C++ program; when used inside of a @catch block, the @throw may appear without an argument (as shown above), in which case the object caught by the @catch will be rethrown.
Note that only (pointers to) Objective-C objects may be thrown and caught using this scheme. When an object is thrown, it will be caught by the nearest @catch clause capable of handling objects of that type, analogously to how "catch" blocks work in C++ and Java. A "@catch(id ...)" clause (as shown above) may also be provided to catch any and all Objective-C exceptions not caught by previous @catch clauses (if any).
The @finally clause, if present, will be executed upon exit from the immediately preceding "@try ... @catch" section. This will happen regardless of whether any exceptions are thrown, caught or rethrown inside the "@try ... @catch" section, analogously to the behavior of the "finally" clause in Java.
There are several caveats to using the new exception mechanism:
-
- *
- Although currently designed to be binary compatible with "NS_HANDLER"-style idioms provided by the "NSException" class, the new exceptions can only be used on Mac OS X 10.3 (Panther) and later systems, due to additional functionality needed in the (NeXT) Objective-C runtime.
- *
- As mentioned above, the new exceptions do not support handling types other than Objective-C objects. Furthermore, when used from Objective-C++, the Objective-C exception model does not interoperate with C++ exceptions at this time. This means you cannot @throw an exception from Objective-C and "catch" it in C++, or vice versa (i.e., "throw ... @catch").
-
The -fobjc-exceptions switch also enables the use of synchronization blocks for thread-safe execution:
@synchronized (ObjCClass *guard) { ... }
Upon entering the @synchronized block, a thread of execution shall first check whether a lock has been placed on the corresponding "guard" object by another thread. If it has, the current thread shall wait until the other thread relinquishes its lock. Once "guard" becomes available, the current thread will place its own lock on it, execute the code contained in the @synchronized block, and finally relinquish the lock (thereby making "guard" available to other threads).
Unlike Java, Objective-C does not allow for entire methods to be marked @synchronized. Note that throwing exceptions out of @synchronized blocks is allowed, and will cause the guarding object to be unlocked properly.
-
- -fobjc-gc
- Enable garbage collection (GC) in Objective-C and Objective-C++ programs.
- -freplace-objc-classes
- Emit a special marker instructing ld(1) not to statically link in the resulting object file, and allow dyld(1) to load it in at run time instead. This is used in conjunction with the Fix-and-Continue debugging mode, where the object file in question may be recompiled and dynamically reloaded in the course of program execution, without the need to restart the program itself. Currently, Fix-and-Continue functionality is only available in conjunction with the NeXT runtime on Mac OS X 10.3 and later.
- -fzero-link
- When compiling for the NeXT runtime, the compiler ordinarily replaces calls to "objc_getClass("...")" (when the name of the class is known at compile time) with static class references that get initialized at load time, which improves run-time performance. Specifying the -fzero-link flag suppresses this behavior and causes calls to "objc_getClass("...")" to be retained. This is useful in Zero-Link debugging mode, since it allows for individual class implementations to be modified during program execution.
- -gen-decls
- Dump interface declarations for all classes seen in the source file to a file named sourcename.decl.
- -Wassign-intercept (Objective-C and Objective-C++ only)
- Warn whenever an Objective-C assignment is being intercepted by the garbage collector.
- -Wno-protocol (Objective-C and Objective-C++ only)
- If a class is declared to implement a protocol, a warning is issued for every method in the protocol that is not implemented by the class. The default behavior is to issue a warning for every method not explicitly implemented in the class, even if a method implementation is inherited from the superclass. If you use the -Wno-protocol option, then methods inherited from the superclass are considered to be implemented, and no warning is issued for them.
- -Wselector (Objective-C and Objective-C++ only)
- Warn if multiple methods of different types for the same selector are found during compilation. The check is performed on the list of methods in the final stage of compilation. Additionally, a check is performed for each selector appearing in a "@selector(...)" expression, and a corresponding method for that selector has been found during compilation. Because these checks scan the method table only at the end of compilation, these warnings are not produced if the final stage of compilation is not reached, for example because an error is found during compilation, or because the -fsyntax-only option is being used.
- -Wstrict-selector-match (Objective-C and Objective-C++ only)
- Warn if multiple methods with differing argument and/or return types are found for a given selector when attempting to send a message using this selector to a receiver of type "id" or "Class". When this flag is off (which is the default behavior), the compiler will omit such warnings if any differences found are confined to types which share the same size and alignment.
- -Wundeclared-selector (Objective-C and Objective-C++ only)
- Warn if a "@selector(...)" expression referring to an undeclared selector is found. A selector is considered undeclared if no method with that name has been declared before the "@selector(...)" expression, either explicitly in an @interface or @protocol declaration, or implicitly in an @implementation section. This option always performs its checks as soon as a "@selector(...)" expression is found, while -Wselector only performs its checks in the final stage of compilation. This also enforces the coding style convention that methods and selectors must be declared before being used.
- -print-objc-runtime-info
- Generate C header describing the largest structure that is passed by value, if any.
Options to Control Diagnostic Messages Formatting
Traditionally, diagnostic messages have been formatted irrespective of the output device's aspect (e.g. its width, ...). The options described below can be used to control the diagnostic messages formatting algorithm, e.g. how many characters per line, how often source location information should be reported. Right now, only the C++ front end can honor these options. However it is expected, in the near future, that the remaining front ends would be able to digest them correctly.- -fmessage-length=n
- Try to format error messages so that they fit on lines of about n characters. The default is 72 characters for g++ and 0 for the rest of the front ends supported by GCC. If n is zero, then no line-wrapping will be done; each error message will appear on a single line.
- -fdiagnostics-show-location=once
- Only meaningful in line-wrapping mode. Instructs the diagnostic messages reporter to emit once source location information; that is, in case the message is too long to fit on a single physical line and has to be wrapped, the source location won't be emitted (as prefix) again, over and over, in subsequent continuation lines. This is the default behavior.
- -fdiagnostics-show-location=every-line
- Only meaningful in line-wrapping mode. Instructs the diagnostic messages reporter to emit the same source location information (as prefix) for physical lines that result from the process of breaking a message which is too long to fit on a single line.
- -fdiagnostics-show-option
- This option instructs the diagnostic machinery to add text to each diagnostic emitted, which indicates which command line option directly controls that diagnostic, when such an option is known to the diagnostic machinery.
- -Wcoverage-mismatch
- 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, GCC emits an error message in this case. The option -Wcoverage-mismatch emits a warning instead of an error. GCC does not use appropriate feedback profiles, so using this option can result in poorly optimized code. This option is useful only in the case of very minor changes such as bug fixes to an existing code-base.
Options to Request or Suppress Warnings
Warnings are diagnostic messages that report constructions which are not inherently erroneous but which are risky or suggest there may have been an error.The following language-independent options do not enable specific warnings but control the kinds of diagnostics produced by GCC.
- -fsyntax-only
- Check the code for syntax errors, but don't do anything beyond that.
- -w
- Inhibit all warning messages.
- -Werror
- Make all warnings into errors.
- -Werror=
-
Make the specified warning into an error. The specifier for a warning
is appended, for example -Werror=switch turns the warnings
controlled by -Wswitch into errors. This switch takes a
negative form, to be used to negate -Werror for specific
warnings, for example -Wno-error=switch makes
-Wswitch warnings not be errors, even when -Werror
is in effect. You can use the -fdiagnostics-show-option
option to have each controllable warning amended with the option which
controls it, to determine what to use with this option.
Note that specifying -Werror=foo automatically implies -Wfoo. However, -Wno-error=foo does not imply anything.
- -Wfatal-errors
- This option causes the compiler to abort compilation on the first error occurred rather than trying to keep going and printing further error messages.
You can request many specific warnings with options beginning -W, for example -Wimplicit to request warnings on implicit declarations. Each of these specific warning options also has a negative form beginning -Wno- to turn off warnings; for example, -Wno-implicit. This manual lists only one of the two forms, whichever is not the default. For further, language-specific options also refer to C++ Dialect Options and Objective-C and Objective-C++ Dialect Options.
- -pedantic
-
Issue all the warnings demanded by strict ISO C and ISO C++;
reject all programs that use forbidden extensions, and some other
programs that do not follow ISO C and ISO C++. For ISO C, follows the
version of the ISO 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 will require -ansi or a -std option specifying the required version of ISO C). However, without this option, certain GNU extensions and traditional C and C++ features are supported as well. With this option, they are rejected.
-pedantic does not cause warning messages for use of the alternate keywords whose names begin and end with __. Pedantic warnings are also disabled in the expression that follows "__extension__". However, only system header files should use these escape routes; application programs should avoid them.
Some users try to use -pedantic to check programs for strict ISO C conformance. They soon find that it does not do quite what they want: it finds some non-ISO practices, but not all---only those for which ISO C requires a diagnostic, and some others for which diagnostics have been added.
A feature to report any failure to conform to ISO C might be useful in some instances, but would require considerable additional work and would be quite different from -pedantic. We don't have plans to support such a feature in the near future.
Where the standard specified with -std represents a GNU extended dialect of C, such as gnu89 or gnu99, there is a corresponding base standard, the version of ISO C on which the GNU extended dialect is based. Warnings from -pedantic are given where they are required by the base standard. (It would not make sense for such warnings to be given only for features not in the specified GNU C dialect, since by definition the GNU dialects of C include all features the compiler supports with the given option, and there would be nothing to warn about.)
- -pedantic-errors
- Like -pedantic, except that errors are produced rather than warnings.
- -Wall
-
This enables all the warnings about constructions that some users
consider questionable, and that are easy to avoid (or modify to
prevent the warning), even in conjunction with macros. This also
enables some language-specific warnings described in C++ Dialect
Options and Objective-C and Objective-C++ Dialect Options.
-Wall turns on the following warning flags:
-Waddress -Warray-bounds (only with -O2) -Wc++0x-compat -Wchar-subscripts -Wimplicit-int -Wimplicit-function-declaration -Wcomment -Wformat -Wmain (only for C/ObjC and unless -ffreestanding) -Wmissing-braces -Wnonnull -Wparentheses -Wpointer-sign -Wreorder -Wreturn-type -Wsequence-point -Wsign-compare (only in C++) -Wstrict-aliasing -Wstrict-overflow=1 -Wswitch -Wtrigraphs -Wuninitialized -Wunknown-pragmas -Wunused-function -Wunused-label -Wunused-value -Wunused-variable -Wvolatile-register-var
Note that some warning flags are not implied by -Wall. Some of them warn about constructions that users generally do not consider questionable, but which occasionally you might wish to check for; others warn about constructions that are necessary or hard to avoid in some cases, and there is no simple way to modify the code to suppress the warning. Some of them are enabled by -Wextra but many of them must be enabled individually.
- -Wextra
-
This enables some extra warning flags that are not enabled by
-Wall. (This option used to be called -W. The older
name is still supported, but the newer name is more descriptive.)
-Wclobbered -Wempty-body -Wignored-qualifiers -Wmissing-field-initializers -Wmissing-parameter-type (C only) -Wold-style-declaration (C only) -Woverride-init -Wsign-compare -Wtype-limits -Wuninitialized -Wunused-parameter (only with -Wunused or -Wall)
The option -Wextra also prints warning messages for the following cases:
-
- *
- A pointer is compared against integer zero with <, <=, >, or >=.
- *
- (C++ only) An enumerator and a non-enumerator both appear in a conditional expression.
- *
- (C++ only) Ambiguous virtual bases.
- *
- (C++ only) Subscripting an array which has been declared register.
- *
- (C++ only) Taking the address of a variable which has been declared register.
- *
- (C++ only) A base class is not initialized in a derived class' copy constructor.
-
- -Wchar-subscripts
- 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.
- -Wcomment
- 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.
- -Wformat
-
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).
Since -Wformat also checks for null format arguments for several functions, -Wformat also implies -Wnonnull.
-Wformat is included in -Wall. For more control over some aspects of format checking, the options -Wformat-y2k, -Wno-format-extra-args, -Wno-format-zero-length, -Wformat-nonliteral, -Wformat-security, and -Wformat=2 are available, but are not included in -Wall.
- -Wformat-y2k
- If -Wformat is specified, also warn about "strftime" formats which may yield only a two-digit year.
- -Wno-format-contains-nul
- If -Wformat is specified, do not warn about format strings that contain NUL bytes.
- -Wno-format-extra-args
-
If -Wformat is specified, do not warn about excess arguments to a
"printf" or "scanf" format function. The C standard specifies
that such arguments are ignored.
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.
- -Wno-format-zero-length (C and Objective-C only)
- If -Wformat is specified, do not warn about zero-length formats. The C standard specifies that zero-length formats are allowed.
- -Wformat-nonliteral
- If -Wformat is specified, also warn if the format string is not a string literal and so cannot be checked, unless the format function takes its format arguments as a "va_list".
- -Wformat-security
- If -Wformat is specified, also warn about uses of format functions that 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=2
- Enable -Wformat plus format checks not included in -Wformat. Currently equivalent to -Wformat -Wformat-nonliteral -Wformat-security -Wformat-y2k.
- -Wnonnull (C and Objective-C only)
-
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.
- -Winit-self (C, C++, Objective-C and Objective-C++ only)
-
Warn about uninitialized variables which are initialized with themselves.
Note this option can only be used with the -Wuninitialized option.
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; }
- -Wimplicit-int (C and Objective-C only)
- Warn when a declaration does not specify a type. This warning is enabled by -Wall.
- -Wimplicit-function-declaration (C and Objective-C only)
- Give a warning whenever a function is used before being declared. In C99 mode (-std=c99 or -std=gnu99), this warning is enabled by default and it is made into an error by -pedantic-errors. This warning is also enabled by -Wall.
- -Wimplicit
- Same as -Wimplicit-int and -Wimplicit-function-declaration. This warning is enabled by -Wall.
- -Wignored-qualifiers (C and C++ only)
-
Warn if the return type of a function has a type qualifier
such as "const". For ISO C such a type qualifier has no effect,
since the value returned by a function 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.
- -Wmain
- Warn if the type of main is suspicious. main should be a function with external linkage, returning int, taking either zero arguments, two, or three arguments of appropriate types. This warning is enabled by default in C++ and is enabled by either -Wall or -pedantic.
- -Wmissing-braces
-
Warn if an aggregate or union initializer is not fully bracketed. In
the following example, the initializer for a is not fully
bracketed, but that for b is fully bracketed.
int a[2][2] = { 0, 1, 2, 3 }; int b[2][2] = { { 0, 1 }, { 2, 3 } };
This warning is enabled by -Wall.
- -Wmissing-include-dirs (C, C++, Objective-C and Objective-C++ only)
- Warn if a user-supplied include directory does not exist.
- -Wparentheses
-
Warn if parentheses are omitted in certain contexts, such
as when there is an assignment in a context where a truth value
is expected, or when operators are nested whose precedence people
often get confused about.
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 (); } }
This warning is enabled by -Wall.
- -Wsequence-point
-
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>.
This warning is enabled by -Wall for C and C++.
- -Wreturn-type
-
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 a
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.
This warning is enabled by -Wall.
- -Wswitch
- Warn whenever a "switch" statement has an index of enumerated type and lacks a "case" for one or more of the named codes of that enumeration. (The presence of a "default" label prevents this warning.) "case" labels outside the enumeration range also provoke warnings when this option is used. This warning is enabled by -Wall.
- -Wswitch-default
- Warn whenever a "switch" statement does not have a "default" case.
- -Wswitch-enum
- Warn whenever a "switch" statement has an index of enumerated type and lacks a "case" for one or more of the named codes of that enumeration. "case" labels outside the enumeration range also provoke warnings when this option is used.
- -Wsync-nand (C and C++ only)
- Warn when "__sync_fetch_and_nand" and "__sync_nand_and_fetch" built-in functions are used. These functions changed semantics in GCC 4.4.
- -Wtrigraphs
- Warn if any trigraphs are encountered that might change the meaning of the program (trigraphs within comments are not warned about). This warning is enabled by -Wall.
- -Wunused-but-set-parameter
-
Warn whenever a function parameter is assigned to, but otherwise unused
(aside from its declaration).
To suppress this warning use the unused attribute.
- -Wunused-but-set-variable
-
Warn whenever a local variable is assigned to, but otherwise unused
(aside from its declaration).
To suppress this warning use the unused attribute.
- -Wunused-function
- Warn whenever a static function is declared but not defined or a non-inline static function is unused. This warning is enabled by -Wall.
- -Wunused-label
-
Warn whenever a label is declared but not used.
This warning is enabled by -Wall.
To suppress this warning use the unused attribute.
- -Wunused-parameter
-
Warn whenever a function parameter is unused aside from its declaration.
To suppress this warning use the unused attribute.
- -Wunused-variable
-
Warn whenever a local variable or non-constant static variable is unused
aside from its declaration.
This warning is enabled by -Wall.
To suppress this warning use the unused attribute.
- -Wunused-value
-
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.
This warning is enabled by -Wall.
- -Wunused
-
All the above -Wunused options combined.
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.
- -Wuninitialized
-
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".
This warning is enabled by -Wall or -Wextra.
- -Wunknown-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.
- -Wno-pragmas
- Do not warn about misuses of pragmas, such as incorrect parameters, invalid syntax, or conflicts between pragmas. See also -Wunknown-pragmas.
- -Wstrict-aliasing
- This option is only active when -fstrict-aliasing is active. It warns 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. It is included in -Wall. It is equivalent to -Wstrict-aliasing=3
- -Wstrict-aliasing=n
-
This option is only active when -fstrict-aliasing is active.
It warns about code which 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=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 punn+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.
- -Wstrict-overflow
- -Wstrict-overflow=n
-
This option is only active when -fstrict-overflow is active.
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 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.
-
- -Warray-bounds
- 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. This warning is enabled by -Wall.
- -Wno-div-by-zero
- Do not warn about compile-time integer division by zero. Floating point division by zero is not warned about, as it can be a legitimate way of obtaining infinities and NaNs.
- -Wsystem-headers
- 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 will not warn about unknown pragmas in system headers---for that, -Wunknown-pragmas must also be used.
- -Wfloat-equal
-
Warn if floating point values are used in equality comparisons.
The idea behind this is that sometimes it is convenient (for the programmer) to consider floating-point values as approximations to infinitely precise real numbers. If you are doing this, then you need to compute (by analyzing the code, or in some other way) the maximum or likely maximum error that the computation introduces, and allow for it when performing comparisons (and when producing output, but that's a different problem). In particular, instead of testing for equality, you 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.
- -Wtraditional (C and Objective-C only)
-
Warn about certain constructs that behave differently in traditional and
ISO C. Also warn about ISO C constructs that have no traditional C
equivalent, and/or problematic constructs 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.
-
- -Wtraditional-conversion (C and Objective-C only)
- Warn if a prototype causes a type conversion that is different from what would happen to the same argument in the absence of a prototype. This includes conversions of fixed point to floating and vice versa, and conversions changing the width or signedness of a fixed point argument except when the same as the default promotion.
- -Wdeclaration-after-statement (C and Objective-C only)
- Warn when a declaration is found after a statement in a block. This construct, known from C++, was introduced with ISO C99 and is by default allowed in GCC. It is not supported by ISO C90 and was not supported by GCC versions before GCC 3.0.
- -Wundef
- Warn if an undefined identifier is evaluated in an #if directive.
- -Wno-endif-labels
- Do not warn whenever an #else or an #endif are followed by text.
- -Wshadow
- Warn whenever a local variable shadows another local variable, parameter or global variable or whenever a built-in function is shadowed.
- -Wlarger-than=len
- Warn whenever an object of larger than len bytes is defined.
- -Wframe-larger-than=len
- 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.
- -Wunsafe-loop-optimizations
- 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.
- -Wno-pedantic-ms-format (MinGW targets only)
- Disables the warnings about non-ISO "printf" / "scanf" format width specifiers "I32", "I64", and "I" used on Windows targets depending on the MS runtime, when you are using the options -Wformat and -pedantic without gnu-extensions.
- -Wpointer-arith
- 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 -pedantic.
- -Wtype-limits
- 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.
- -Wbad-function-cast (C and Objective-C only)
- Warn whenever a function call is cast to a non-matching type. For example, warn if "int malloc()" is cast to "anything *".
- -Wc++-compat (C and Objective-C only)
- Warn about ISO C constructs that are outside of the common subset of ISO C and ISO C++, e.g. request for implicit conversion from "void *" to a pointer to non-"void" type.
- -Wc++0x-compat (C++ and Objective-C++ only)
- 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. This warning is enabled by -Wall.
- -Wcast-qual
- Warn whenever a pointer is cast so as to remove a type qualifier from the target type. For example, warn if a "const char *" is cast to an ordinary "char *".
- -Wcast-align
- Warn whenever a pointer is cast such that the required alignment of the target is increased. For example, warn if a "char *" is cast to an "int *" on machines where integers can only be accessed at two- or four-byte boundaries.
- -Wwrite-strings
-
When compiling C, give string constants the type "const
char[length]" so that copying the address of one into a
non-"const" "char *" pointer 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.
- -Wclobbered
- Warn for variables that might be changed by longjmp or vfork. This warning is also enabled by -Wextra.
- -Wconversion
-
Warn for implicit conversions that may alter a value. This includes
conversions between real and integer, like "abs (x)" when
"x" is "double"; conversions between signed and unsigned,
like "unsigned ui = -1"; and conversions to smaller types, like
"sqrtf (M_PI)". Do not warn for explicit casts like "abs
((int) x)" and "ui = (unsigned) -1", or if the value is not
changed by the conversion like in "abs (2.0)". Warnings about
conversions between signed and unsigned integers can be disabled by
using -Wno-sign-conversion.
For C++, also warn for conversions between "NULL" and non-pointer types; 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.
- -Wempty-body
- Warn if an empty body occurs in an if, else or do while statement. This warning is also enabled by -Wextra.
- -Wenum-compare (C++ and Objective-C++ only)
- Warn about a comparison between values of different enum types. This warning is enabled by default.
- -Wsign-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 -Wextra; to get the other warnings of -Wextra without this warning, use -Wextra -Wno-sign-compare.
- -Wsign-conversion
- Warn for implicit conversions that may change the sign of an integer value, like assigning a signed integer expression to an unsigned integer variable. An explicit cast silences the warning. In C, this option is enabled also by -Wconversion.
- -Waddress
- 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". This warning is enabled by -Wall.
- -Wlogical-op
- Warn about suspicious uses of logical operators in expressions. This includes using logical operators in contexts where a bit-wise operator is likely to be expected.
- -Waggregate-return
- Warn if any functions that return structures or unions are defined or called. (In languages where you can return an array, this also elicits a warning.)
- -Wno-attributes
- Do not 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.
- -Wno-builtin-macro-redefined
- Do not warn if certain built-in macros are redefined. This suppresses warnings for redefinition of "__TIMESTAMP__", "__TIME__", "__DATE__", "__FILE__", and "__BASE_FILE__".
- -Wstrict-prototypes (C and Objective-C only)
- Warn if a function is declared or defined without specifying the argument types. (An old-style function definition is permitted without a warning if preceded by a declaration which specifies the argument types.)
- -Wold-style-declaration (C and Objective-C only)
- Warn for obsolescent usages, according to the C Standard, in a declaration. For example, warn if storage-class specifiers like "static" are not the first things in a declaration. This warning is also enabled by -Wextra.
- -Wold-style-definition (C and Objective-C only)
- Warn if an old-style function definition is used. A warning is given even if there is a previous prototype.
- -Wmissing-parameter-type (C and Objective-C only)
-
A function parameter is declared without a type specifier in K&R-style
functions:
void foo(bar) { }
This warning is also enabled by -Wextra.
- -Wmissing-prototypes (C and Objective-C only)
- Warn if a global function is defined without a previous prototype declaration. This warning is issued even if the definition itself provides a prototype. The aim is to detect global functions that fail to be declared in header files.
- -Wmissing-declarations
- Warn if a global function is defined without a previous declaration. Do so even if the definition itself provides a prototype. Use this option to detect global functions that are not declared in header files. In C++, no warnings are issued for function templates, or for inline functions, or for functions in anonymous namespaces.
- -Wmissing-field-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 };
This warning is included in -Wextra. To get other -Wextra warnings without this one, use -Wextra -Wno-missing-field-initializers.
- -Wmissing-noreturn
- Warn about functions which might be candidates for attribute "noreturn". Note these are only possible candidates, not absolute ones. Care should be taken to manually verify functions actually do not ever return before adding the "noreturn" attribute, otherwise subtle code generation bugs could be introduced. You will not get a warning for "main" in hosted C environments.
- -Wmissing-format-attribute
-
Warn about function pointers which 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 which 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.
- -Wno-multichar
- Do not warn if a multicharacter constant ('FOOF') is used. Usually they indicate a typo in the user's code, as they have implementation-defined values, and should not be used in portable code.
- -Wnormalized=<none|id|nfc|nfkc>
-
In ISO C and ISO C++, two identifiers are different if they are
different sequences of characters. However, sometimes when characters
outside the basic ASCII character set are used, you can have two
different character sequences that look the same. To avoid confusion,
the ISO 10646 standard sets out some normalization rules which
when applied ensure that two sequences that look the same are turned into
the same sequence. GCC can warn you if you are using identifiers which
have not been normalized; this option controls that warning.
There are four levels of warning that GCC supports. The default is -Wnormalized=nfc, which warns about any identifier which is not in the ISO 10646 ``C'' normalized form, NFC. NFC is the recommended form for most uses.
Unfortunately, there are some characters which ISO C and ISO C++ allow in identifiers that when turned into NFC aren't allowable as 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" which 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.
- -Wno-deprecated
- Do not warn about usage of deprecated features.
- -Wno-deprecated-declarations
- Do not warn about uses of functions, variables, and types marked as deprecated by using the "deprecated" attribute.
- -Wno-overflow
- Do not warn about compile-time overflow in constant expressions.
- -Woverride-init (C and Objective-C only)
-
Warn if an initialized field without side effects is overridden when
using designated initializers.
This warning is included in -Wextra. To get other -Wextra warnings without this one, use -Wextra -Wno-override-init.
- -Wpacked
-
Warn if a structure is given the packed attribute, but the packed
attribute has no effect on the layout or size of the structure.
Such structures may be mis-aligned 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; };
- -Wpacked-bitfield-compat
-
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));
This warning is enabled by default. Use -Wno-packed-bitfield-compat to disable this warning.
- -Wpadded
- Warn if padding is included in a structure, either to align an element of the structure or to align the whole structure. Sometimes when this happens it is possible to rearrange the fields of the structure to reduce the padding and so make the structure smaller.
- -Wredundant-decls
- Warn if anything is declared more than once in the same scope, even in cases where multiple declaration is valid and changes nothing.
- -Wnested-externs (C and Objective-C only)
- Warn if an "extern" declaration is encountered within a function.
- -Wunreachable-code
-
Warn if the compiler detects that code will never be executed.
This option is intended to warn when the compiler detects that at least a whole line of source code will never be executed, because some condition is never satisfied or because it is after a procedure that never returns.
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.
This option is not made part of -Wall because in a debugging version of a program there is often substantial code which checks correct functioning of the program and is, hopefully, unreachable because the program does work. Another common use of unreachable code is to provide behavior which is selectable at compile-time.
- -Winline
-
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.
- -Wno-invalid-offsetof (C++ and Objective-C++ only)
-
Suppress warnings from 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.) 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.
- -Wno-int-to-pointer-cast (C and Objective-C only)
- Suppress warnings from casts to pointer type of an integer of a different size.
- -Wno-pointer-to-int-cast (C and Objective-C only)
- Suppress warnings from casts from a pointer to an integer type of a different size.
- -Winvalid-pch
- Warn if a precompiled header is found in the search path but can't be used.
- -Wlong-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.
- -Wvariadic-macros
- Warn if variadic macros are used in pedantic ISO C90 mode, or the GNU alternate syntax when in pedantic ISO C99 mode. This is default. To inhibit the warning messages, use -Wno-variadic-macros.
- -Wvla
- Warn if variable length array is used in the code. -Wno-vla will prevent the -pedantic warning of the variable length array.
- -Wvolatile-register-var
- 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.
- -Wdisabled-optimization
- 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.
- -Wpointer-sign (C and Objective-C only)
- 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 -pedantic, which can be disabled with -Wno-pointer-sign.
- -Wstack-protector
- This option is only active when -fstack-protector is active. It warns about functions that will not be protected against stack smashing.
- -Wno-mudflap
- Suppress warnings about constructs that cannot be instrumented by -fmudflap.
- -Woverlength-strings
-
Warn about string constants which are longer than the ``minimum
maximum'' length specified in the C standard. Modern compilers
generally allow string constants which 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 C89, 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 -pedantic, and can be disabled with -Wno-overlength-strings.
Options for Debugging Your Program or GCC
GCC has various special options that are used for debugging either your program or GCC:- -g
-
Produce debugging information in the operating system's native format
(stabs, COFF, XCOFF, or DWARF 2). GDB can work with this debugging
information.
On most systems that use stabs format, -g enables use of extra debugging information that only GDB can use; this extra information makes debugging work better in GDB but will probably make other debuggers crash or refuse to read the program. If you want to control for certain whether to generate the extra information, use -gstabs+, -gstabs, -gxcoff+, -gxcoff, or -gvms (see below).
GCC allows you to use -g with -O. The shortcuts taken by optimized code may occasionally produce surprising results: some variables you declared may not exist at all; flow of control may briefly move where you did not expect it; some statements may not be executed because they compute constant results or their values were already at hand; some statements may execute in different places because they were moved out of loops.
Nevertheless it proves possible to debug optimized output. This makes it reasonable to use the optimizer for programs that might have bugs.
The following options are useful when GCC is generated with the capability for more than one debugging format.
- -ggdb
- Produce debugging information for use by GDB. This means to use the most expressive format available (DWARF 2, stabs, or the native format if neither of those are supported), including GDB extensions if at all possible.
- -gstabs
- Produce debugging information in stabs format (if that is supported), without GDB extensions. This is the format used by DBX on most BSD systems. On MIPS, Alpha and System V Release 4 systems this option produces stabs debugging output which is not understood by DBX or SDB. On System V Release 4 systems this option requires the GNU assembler.
- -feliminate-unused-debug-symbols
- Produce debugging information in stabs format (if that is supported), for only symbols that are actually used.
- -femit-class-debug-always
- Instead of emitting debugging information for a C++ class in only one object file, emit it in all object files using the class. This option should be used only with debuggers that are unable to handle the way GCC normally emits debugging information for classes because using this option will increase the size of debugging information by as much as a factor of two.
- -gstabs+
- Produce debugging information in stabs format (if that is supported), using GNU extensions understood only by the GNU debugger (GDB). The use of these extensions is likely to make other debuggers crash or refuse to read the program.
- -gcoff
- Produce debugging information in COFF format (if that is supported). This is the format used by SDB on most System V systems prior to System V Release 4.
- -gxcoff
- Produce debugging information in XCOFF format (if that is supported). This is the format used by the DBX debugger on IBM RS/6000 systems.
- -gxcoff+
- Produce debugging information in XCOFF format (if that is supported), using GNU extensions understood only by the GNU debugger (GDB). The use of these extensions is likely to make other debuggers crash or refuse to read the program, and may cause assemblers other than the GNU assembler (GAS) to fail with an error.
- -gdwarf-version
-
Produce debugging information in DWARF format (if that is
supported). This is the format used by DBX on IRIX 6. The value
of version may be either 2 or 3; the default version is 3.
Note that with DWARF version 2 some ports require, and will always use, some non-conflicting DWARF 3 extensions in the unwind tables.
- -gstrict-dwarf
- Disallow using extensions of later DWARF standard version than selected with -gdwarf-version. On most targets using non-conflicting DWARF extensions from later standard versions is allowed.
- -gno-strict-dwarf
- Allow using extensions of later DWARF standard version than selected with -gdwarf-version.
- -gvms
- Produce debugging information in VMS debug format (if that is supported). This is the format used by DEBUG on VMS systems.
- -glevel
- -ggdblevel
- -gstabslevel
- -gcofflevel
- -gxcofflevel
- -gvmslevel
-
Request debugging information and also use level to specify how
much information. The default level is 2.
Level 0 produces no debug information at all. Thus, -g0 negates -g.
Level 1 produces minimal information, enough for making backtraces in parts of the program that you don't plan to debug. This includes descriptions of functions and external variables, but no information about local variables and no line numbers.
Level 3 includes extra information, such as all the macro definitions present in the program. Some debuggers support macro expansion when you use -g3.
-gdwarf-2 does not accept a concatenated debug level, because GCC used to support an option -gdwarf that meant to generate debug information in version 1 of the DWARF format (which is very different from version 2), and it would have been too confusing. That debug format is long obsolete, but the option cannot be changed now. Instead use an additional -glevel option to change the debug level for DWARF.
- -gtoggle
- Turn off generation of debug info, if leaving out this option would have generated it, or turn it on at level 2 otherwise. The position of this argument in the command line does not matter, it takes effect after all other options are processed, and it does so only once, no matter how many times it is given. This is mainly intended to be used with -fcompare-debug.
- -fdump-final-insns[=file]
- Dump the final internal representation (RTL) to file. If the optional argument is omitted (or if file is "."), the name of the dump file will be determined by appending ".gkd" to the compilation output file name.
- -fcompare-debug[=opts]
-
If no error occurs during compilation, run the compiler a second time,
adding opts and -fcompare-debug-second to the arguments
passed to the second compilation. Dump the final internal
representation in both compilations, and print an error if they differ.
If the equal sign is omitted, the default -gtoggle is used.
The environment variable GCC_COMPARE_DEBUG, if defined, non-empty and nonzero, implicitly enables -fcompare-debug. If GCC_COMPARE_DEBUG is defined to a string starting with a dash, then it is used for opts, otherwise the default -gtoggle is used.
-fcompare-debug=, with the equal sign but without opts, is equivalent to -fno-compare-debug, which disables the dumping of the final representation and the second compilation, preventing even GCC_COMPARE_DEBUG from taking effect.
To verify full coverage during -fcompare-debug testing, set GCC_COMPARE_DEBUG to say -fcompare-debug-not-overridden, which GCC will reject as an invalid option in any actual compilation (rather than preprocessing, assembly or linking). To get just a warning, setting GCC_COMPARE_DEBUG to -w%n-fcompare-debug not overridden will do.
- -fcompare-debug-second
-
This option is implicitly passed to the compiler for the second
compilation requested by -fcompare-debug, along with options to
silence warnings, and omitting other options that would cause
side-effect compiler outputs to files or to the standard output. Dump
files and preserved temporary files are renamed so as to contain the
".gk" additional extension during the second compilation, to avoid
overwriting those generated by the first.
When this option is passed to the compiler driver, it causes the first compilation to be skipped, which makes it useful for little other than debugging the compiler proper.
- -feliminate-dwarf2-dups
- Compress DWARF2 debugging information by eliminating duplicated information about each symbol. This option only makes sense when generating DWARF2 debugging information with -gdwarf-2.
- -femit-struct-debug-baseonly
-
Emit debug information for struct-like types
only when the base name of the compilation source file
matches the base name of file in which the struct was defined.
This option substantially reduces the size of debugging information, but at significant potential loss in type information to the debugger. See -femit-struct-debug-reduced for a less aggressive option. See -femit-struct-debug-detailed for more detailed control.
This option works only with DWARF 2.
- -femit-struct-debug-reduced
-
Emit debug information for struct-like types
only when the base name of the compilation source file
matches the base name of file in which the type was defined,
unless the struct is a template or defined in a system header.
This option significantly reduces the size of debugging information, with some potential loss in type information to the debugger. See -femit-struct-debug-baseonly for a more aggressive option. See -femit-struct-debug-detailed for more detailed control.
This option works only with DWARF 2.
- -femit-struct-debug-detailed[=spec-list]
-
Specify the struct-like types
for which the compiler will generate debug information.
The intent is to reduce duplicate struct debug information
between different object files within the same program.
This option is a detailed version of -femit-struct-debug-reduced and -femit-struct-debug-baseonly, which will serve for most needs.
A specification has the syntax [dir:|ind:][ord:|gen:](any|sys|base|none)
The optional first word limits the specification to structs that are used directly (dir:) or used indirectly (ind:). A struct type is used directly when it is the type of a variable, member. Indirect uses arise through pointers to structs. That is, when use of an incomplete struct would be legal, the use is indirect. An example is struct one direct; struct two * indirect;.
The optional second word limits the specification to ordinary structs (ord:) or generic structs (gen:). Generic structs are a bit complicated to explain. For C++, these are non-explicit specializations of template classes, or non-template classes within the above. Other programming languages have generics, but -femit-struct-debug-detailed does not yet implement them.
The third word specifies the source files for those structs for which the compiler will emit debug information. The values none and any have the normal meaning. The value base means that the base of name of the file in which the type declaration appears must match the base of the name of the main compilation file. In practice, this means that types declared in foo.c and foo.h will have debug information, but types declared in other header will not. The value sys means those types satisfying base or declared in system or compiler headers.
You may need to experiment to determine the best settings for your application.
The default is -femit-struct-debug-detailed=all.
This option works only with DWARF 2.
- -fno-merge-debug-strings
- Direct the linker to not merge together strings in the debugging information which are identical in different object files. Merging is not supported by all assemblers or linkers. Merging decreases the size of the debug information in the output file at the cost of increasing link processing time. Merging is enabled by default.
- -fdebug-prefix-map=old=new
- When compiling files in directory old, record debugging information describing them as in new instead.
- -fno-dwarf2-cfi-asm
- Emit DWARF 2 unwind info as compiler generated ".eh_frame" section instead of using GAS ".cfi_*" directives.
- -p
- Generate extra code to write profile information suitable for the analysis program prof. You must use this option when compiling the source files you want data about, and you must also use it when linking.
- -pg
- Generate extra code to write profile information suitable for the analysis program gprof. You must use this option when compiling the source files you want data about, and you must also use it when linking.
- -Q
- Makes the compiler print out each function name as it is compiled, and print some statistics about each pass when it finishes.
- -ftime-report
- Makes the compiler print some statistics about the time consumed by each pass when it finishes.
- -fmem-report
- Makes the compiler print some statistics about permanent memory allocation when it finishes.
- -fpre-ipa-mem-report
- -fpost-ipa-mem-report
- Makes the compiler print some statistics about permanent memory allocation before or after interprocedural optimization.
- -fprofile-arcs
- Add code so that program flow arcs are instrumented. During execution the program records how many times each branch and call is executed and how many times it is taken or returns. When the compiled program exits it saves this data to a file called auxname.gcda for each source file. The data may be used for profile-directed optimizations (-fbranch-probabilities), or for test coverage analysis (-ftest-coverage). Each object file's auxname is generated from the name of the output file, if explicitly specified and it is not the final executable, otherwise it is the basename of the source file. In both cases any suffix is removed (e.g. foo.gcda for input file dir/foo.c, or dir/foo.gcda for output file specified as -o dir/foo.o).
- --coverage
-
This option is used to compile and link code instrumented for coverage
analysis. The option is a synonym for -fprofile-arcs
-ftest-coverage (when compiling) and -lgcov (when
linking). See the documentation for those options for more details.
-
- *
- Compile the source files with -fprofile-arcs plus optimization and code generation options. For test coverage analysis, use the additional -ftest-coverage option. You do not need to profile every source file in a program.
- *
- Link your object files with -lgcov or -fprofile-arcs (the latter implies the former).
- *
- Run the program on a representative workload to generate the arc profile information. This may be repeated any number of times. You can run concurrent instances of your program, and provided that the file system supports locking, the data files will be correctly updated. Also "fork" calls are detected and correctly handled (double counting will not happen).
- *
- For profile-directed optimizations, compile the source files again with the same optimization and code generation options plus -fbranch-probabilities.
- *
- For test coverage analysis, use gcov to produce human readable information from the .gcno and .gcda files. Refer to the gcov documentation for further information.
-
With -fprofile-arcs, for each function of your program GCC creates a program flow graph, then finds a spanning tree for the graph. Only arcs that are not on the spanning tree have to be instrumented: the compiler adds code to count the number of times that these arcs are executed. When an arc is the only exit or only entrance to a block, the instrumentation code can be added to the block; otherwise, a new basic block must be created to hold the instrumentation code.
-
- -ftest-coverage
- Produce a notes file that the gcov code-coverage utility can use to show program coverage. Each source file's note file is called auxname.gcno. Refer to the -fprofile-arcs option above for a description of auxname and instructions on how to generate test coverage data. Coverage data will match the source files more closely, if you do not optimize.
- -fdbg-cnt-list
- Print the name and the counter upperbound for all debug counters.
- -fdbg-cnt=counter-value-list
- Set the internal debug counter upperbound. counter-value-list is a comma-separated list of name:value pairs which sets the upperbound of each debug counter name to value. All debug counters have the initial upperbound of UINT_MAX, thus dbg_cnt() returns true always unless the upperbound is set by this option. e.g. With -fdbg-cnt=dce:10,tail_call:0 dbg_cnt(dce) will return true only for first 10 invocations and dbg_cnt(tail_call) will return false always.
- -dletters
- -fdump-rtl-pass
-
Says to make debugging dumps during compilation at times specified by
letters. This is used for debugging the RTL-based passes of the
compiler. The file names for most of the dumps are made by appending a
pass number and a word to the dumpname. dumpname is generated
from the name of the output file, if explicitly specified and it is not
an executable, otherwise it is the basename of the source file. These
switches may have different effects when -E is used for
preprocessing.
Debug dumps can be enabled with a -fdump-rtl switch or some -d option letters. Here are the possible letters for use in pass and letters, and their meanings:
-
- -fdump-rtl-alignments
- Dump after branch alignments have been computed.
- -fdump-rtl-asmcons