[Top] [Contents] [Index] [ ? ]

Using GNU CC

This manual documents how to run and install the GNU compiler, as well as its new features and incompatibilities, and how to report bugs. It corresponds to GCC version 2.96.

1. Compile C, C++, or Objective C  You can compile C or C++ programs.
2. GNU CC Command Options  Command options supported by `gcc'.
3. Extensions to the C Language Family  GNU extensions to the C language family.
4. Extensions to the C++ Language  GNU extensions to the C++ language.
5. Known Causes of Trouble with GNU CC  If you have trouble installing GNU CC.
6. Reporting Bugs  How, why and where to report bugs.
7. How To Get Help with GNU CC  How to find suppliers of support for GNU CC.
8. Contributing to GNU CC Development  How to contribute to testing and developing GNU CC.



Index  Index of concepts and symbol names.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1. Compile C, C++, or Objective C

The C, C++, and Objective C versions of the compiler are integrated; the GNU C compiler can compile programs written in C, C++, or Objective C.

"GCC" is a common shorthand term for the GNU C compiler. This is both the most general name for the compiler, and the name used when the emphasis is on compiling C programs.

When referring to C++ compilation, it is usual to call the compiler "G++". Since there is only one compiler, it is also accurate to call it "GCC" no matter what the language context; however, the term "G++" is more useful when the emphasis is on compiling C++ programs.

We use the name "GNU CC" to refer to the compilation system as a whole, and more specifically to the language-independent part of the compiler. For example, we refer to the optimization options as affecting the behavior of "GNU CC" or sometimes just "the compiler".

Front ends for other languages, such as Ada 9X, Fortran, Modula-3, and Pascal, are under development. These front-ends, like that for C++, are built in subdirectories of GNU CC and link to it. The result is an integrated compiler that can compile programs written in C, C++, Objective C, or any of the languages for which you have installed front ends.

In this manual, we only discuss the options for the C, Objective-C, and C++ compilers and those of the GNU CC core. Consult the documentation of the other front ends for the options to use when compiling programs written in other languages.

G++ is a compiler, not merely a preprocessor. G++ builds object code directly from your C++ program source. There is no intermediate C version of the program. (By contrast, for example, some other implementations use a program that generates a C program from your C++ source.) Avoiding an intermediate C representation of the program means that you get better object code, and better debugging information. The GNU debugger, GDB, works with this information in the object code to give you comprehensive C++ source-level editing capabilities (see section `C and C++' in Debugging with GDB).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2. GNU CC Command Options

When you invoke GNU CC, 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 GNU CC 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.

See section Compiling C++ Programs, for a summary of special options for compiling C++ programs.

The gcc program accepts options and file names as operands. Many options have multiletter names; therefore multiple single-letter options may not be grouped: `-dr' is very different from `-d -r'.

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.

Many options have long names starting with `-f' or with `-W'---for example, `-fforce-mem', `-fstrength-reduce', `-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.

2.1 Option Summary  Brief list of all options, without explanations.
2.2 Options Controlling the Kind of Output  Controlling the kind of output: an executable, object files, assembler files, or preprocessed source.
2.3 Compiling C++ Programs  Compiling C++ programs.
2.4 Options Controlling C Dialect  Controlling the variant of C language compiled.
2.5 Options Controlling C++ Dialect  Variations on C++.
2.6 Options to Request or Suppress Warnings  How picky should the compiler be?
2.7 Options for Debugging Your Program or GNU CC  Symbol tables, measurements, and debugging dumps.
2.8 Options That Control Optimization  How much optimization?
2.9 Options Controlling the Preprocessor  Controlling header files and macro definitions. Also, getting dependency information for Make.
2.10 Passing Options to the Assembler  Passing options to the assembler.
2.11 Options for Linking  Specifying libraries and so on.
2.12 Options for Directory Search  Where to find header files and libraries. Where to find the compiler executable files.
2.13 Specifying Target Machine and Compiler Version  Running a cross-compiler, or an old version of GNU CC.
2.14 Hardware Models and Configurations  Specifying minor hardware or convention variations, such as 68010 vs 68020.
2.15 Options for Code Generation Conventions  Specifying conventions for function calls, data layout and register usage.
2.16 Environment Variables Affecting GNU CC  Env vars that affect GNU CC.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.1 Option Summary

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

Overall Options
See section Options Controlling the Kind of Output.
 
-c  -S  -E  -o file  -pipe  -v  --help  -x language

C Language Options
See section Options Controlling C Dialect.
 
-ansi -flang-isoc9x -fallow-single-precision  -fcond-mismatch  -fno-asm
-fno-builtin  -ffreestanding  -fhosted  -fsigned-bitfields  -fsigned-char
-funsigned-bitfields  -funsigned-char  -fwritable-strings
-traditional  -traditional-cpp  -trigraphs

C++ Language Options
See section Options Controlling C++ Dialect.
 
-fno-access-control  -fcheck-new  -fconserve-space  -fdollars-in-identifiers
-fno-elide-constructors  -fexternal-templates  -ffor-scope  
-fno-for-scope  -fno-gnu-keywords  -fguiding-decls  -fhandle-signatures
-fhonor-std -fhuge-objects  -fno-implicit-templates  -finit-priority
-fno-implement-inlines -fname-mangling-version-n  -fno-default-inline  
-foperator-names  -fno-optional-diags  -fpermissive -frepo  -fstrict-prototype
-fsquangle  -ftemplate-depth-n  -fthis-is-variable  -fvtable-thunks
-nostdinc++  -Wctor-dtor-privacy -Wno-deprecated -Weffc++  
-Wno-non-template-friend 
-Wnon-virtual-dtor  -Wold-style-cast  -Woverloaded-virtual  
-Wno-pmf-conversions  -Wreorder  -Wsign-promo  -Wsynth

Warning Options
See section Options to Request or Suppress Warnings.
 
-fsyntax-only  -pedantic  -pedantic-errors
-w  -W  -Wall  -Waggregate-return  -Wbad-function-cast
-Wcast-align  -Wcast-qual  -Wchar-subscripts  -Wcomment
-Wconversion  -Werror  -Wformat
-Wid-clash-len  -Wimplicit -Wimplicit-int 
-Wimplicit-function-declaration  -Wimport
-Werror-implicit-function-declaration  -Winline
-Wlarger-than-len  -Wlong-long
-Wmain  -Wmissing-declarations  -Wmissing-noreturn
-Wmissing-prototypes  -Wmultichar  -Wnested-externs  -Wno-import  
-Wparentheses -Wpointer-arith  -Wredundant-decls
-Wreturn-type -Wshadow  -Wsign-compare  -Wstrict-prototypes  
-Wswitch  -Wtraditional  
-Wtrigraphs -Wundef  -Wuninitialized  -Wunused  -Wwrite-strings
-Wunknown-pragmas

Debugging Options
See section Options for Debugging Your Program or GCC.
 
-a  -ax  -dletters  -fdump-unnumbered -fpretend-float
-fprofile-arcs  -ftest-coverage
-g  -glevel  -gcoff  -gdwarf  -gdwarf-1  -gdwarf-1+  -gdwarf-2
-ggdb  -gstabs  -gstabs+  -gxcoff  -gxcoff+
-p  -pg  -print-file-name=library  -print-libgcc-file-name
-print-prog-name=program  -print-search-dirs  -save-temps

Optimization Options
See section Options that Control Optimization.
 
-fbranch-probabilities  -foptimize-register-moves
-fcaller-saves  -fcse-follow-jumps  -fcse-skip-blocks
-fdelayed-branch   -fexpensive-optimizations
-ffast-math  -ffloat-store  -fforce-addr  -fforce-mem
-fdata-sections -ffunction-sections  -fgcse 
-finline-functions -finline-limit-n -fkeep-inline-functions
-fno-default-inline -fno-defer-pop  -fno-function-cse
-fno-inline  -fno-peephole  -fomit-frame-pointer -fregmove
-frerun-cse-after-loop  -frerun-loop-opt -fschedule-insns
-fschedule-insns2  -fstrength-reduce  -fthread-jumps
-funroll-all-loops  -funroll-loops
-fmove-all-movables  -freduce-all-givs -fstrict-aliasing
-O  -O0  -O1  -O2  -O3 -Os

Preprocessor Options
See section Options Controlling the Preprocessor.
 
-Aquestion(answer)  -C  -dD  -dM  -dN
-Dmacro[=defn]  -E  -H
-idirafter dir
-include file  -imacros file
-iprefix file  -iwithprefix dir
-iwithprefixbefore dir  -isystem dir -isystem-c++ dir
-M  -MD  -MM  -MMD  -MG  -nostdinc  -P  -trigraphs
-undef  -Umacro  -Wp,option

Assembler Option
See section Passing Options to the Assembler.
 
-Wa,option

Linker Options
See section Options for Linking.
 
object-file-name  -llibrary
-nostartfiles  -nodefaultlibs  -nostdlib
-s  -static  -shared  -symbolic
-Wl,option  -Xlinker option
-u symbol

Directory Options
See section Options for Directory Search.
 
-Bprefix  -Idir  -I-  -Ldir  -specs=file

Target Options
See section 2.13 Specifying Target Machine and Compiler Version.
 
-b machine  -V version

Machine Dependent Options
See section Hardware Models and Configurations.
 
M680x0 Options
-m68000  -m68020  -m68020-40  -m68020-60  -m68030  -m68040
-m68060  -mcpu32 -m5200  -m68881  -mbitfield  -mc68000  -mc68020  
-mfpa -mnobitfield  -mrtd  -mshort  -msoft-float  -mpcrel
-malign-int


SPARC Options
-mcpu=cpu type
-mtune=cpu type
-mcmodel=code model
-malign-jumps=num  -malign-loops=num
-malign-functions=num
-m32  -m64
-mapp-regs  -mbroken-saverestore  -mcypress  -mepilogue
-mflat  -mfpu  -mhard-float  -mhard-quad-float
-mimpure-text  -mlive-g0  -mno-app-regs  -mno-epilogue
-mno-flat  -mno-fpu  -mno-impure-text
-mno-stack-bias  -mno-unaligned-doubles
-msoft-float  -msoft-quad-float  -msparclite  -mstack-bias
-msupersparc  -munaligned-doubles  -mv8


ARM Options
-mapcs-frame -mno-apcs-frame
-mapcs-26 -mapcs-32
-mapcs-stack-check -mno-apcs-stack-check
-mapcs-float -mno-apcs-float
-mapcs-reentrant -mno-apcs-reentrant
-msched-prolog -mno-sched-prolog
-mlittle-endian -mbig-endian -mwords-little-endian
-mshort-load-bytes -mno-short-load-bytes -mshort-load-words -mno-short-load-words
-msoft-float -mhard-float -mfpe
-mthumb-interwork -mno-thumb-interwork
-mcpu= -march= -mfpe= 
-mstructure-size-boundary=
-mbsd -mxopen -mno-symrename
-mabort-on-noreturn
-mno-sched-prolog
-mlongcall -fbitfield-access-32bit

Thumb Options
-mtpcs-frame -mno-tpcs-frame
-mtpcs-leaf-frame -mno-tpcs-leaf-frame
-mlittle-endian  -mbig-endian
-mthumb-interwork -mno-thumb-interwork
-mstructure-size-boundary=


RS/6000 and PowerPC Options
-mcpu=cpu type
-mtune=cpu type
-mpower  -mno-power  -mpower2  -mno-power2
-mpowerpc  -mno-powerpc
-mpowerpc-gpopt  -mno-powerpc-gpopt
-mpowerpc-gfxopt  -mno-powerpc-gfxopt
-mnew-mnemonics  -mno-new-mnemonics
-mfull-toc   -mminimal-toc  -mno-fop-in-toc  -mno-sum-in-toc
-maix64  -maix32  -mxl-call  -mno-xl-call  -mthreads  -mpe
-msoft-float  -mhard-float  -mmultiple  -mno-multiple
-mstring  -mno-string  -mupdate  -mno-update
-mfused-madd  -mno-fused-madd  -mbit-align  -mno-bit-align
-mstrict-align  -mno-strict-align  -mrelocatable
-mno-relocatable  -mrelocatable-lib  -mno-relocatable-lib
-mtoc  -mno-toc -mlittle  -mlittle-endian  -mbig  -mbig-endian
-mcall-aix  -mcall-sysv  -mprototype  -mno-prototype
-msim  -mmvme  -mads  -myellowknife  -memb -msdata
-msdata=opt  -G num
-mlongcall


MIPS Options
-mabicalls  -mcpu=cpu type  -membedded-data
-membedded-pic  -mfp32  -mfp64  -mgas  -mgp32  -mgp64
-mgpopt  -mhalf-pic  -mhard-float  -mint64  -mips1
-mips2  -mips3  -mips4  -mips5  -mips32 -mips64
-mlong64  -mlong32  -mlong-calls  -mmemcpy
-mmips-as  -mmips-tfile  -mno-abicalls
-mno-embedded-data  -mno-embedded-pic
-mno-gpopt  -mno-long-calls
-mno-memcpy  -mno-mips-tfile  -mno-rnames  -mno-stats
-mrnames  -msoft-float
-m4650  -msingle-float  -mmad
-mstats  -EL  -EB  -G num  -nocpp
-mabi=32 -mabi=n32 -mabi=64 -mabi=eabi

i386 Options
-mcpu=cpu type
-march=cpu type
-mieee-fp  -mno-fancy-math-387
-mno-fp-ret-in-387  -msoft-float  -msvr3-shlib
-mno-wide-multiply  -mrtd  -malign-double
-mreg-alloc=list  -mregparm=num
-malign-jumps=num  -malign-loops=num
-malign-functions=num -mpreferred-stack-boundary=num


SH Options
-ml -mb -m1 -m2 -m3 -m3e -m4single-only -m4-single -m4 -mrelax
-mbigtable -mdalign -mfmovd -mhitachi -mieee -mno-ieee -misize
-mpadstruct -mspace

Code Generation Options
See section Options for Code Generation Conventions.
 
-fcall-saved-reg  -fcall-used-reg
-fexceptions -ffixed-reg  -finhibit-size-directive
-fcheck-memory-usage  -fprefix-function-name
-fno-common  -fno-ident  -fno-gnu-linker
-fpcc-struct-return  -fpic  -fPIC
-freg-struct-return  -fshared-data  -fshort-enums
-fshort-double  -fvolatile  -fvolatile-global -fvolatile-static
-fverbose-asm -fpack-struct  -fstack-check
-fargument-alias  -fargument-noalias
-fargument-noalias-global
-fleading-underscore

2.2 Options Controlling the Kind of Output  Controlling the kind of output: an executable, object files, assembler files, or preprocessed source.
2.4 Options Controlling C Dialect  Controlling the variant of C language compiled.
2.5 Options Controlling C++ Dialect  Variations on C++.
2.6 Options to Request or Suppress Warnings  How picky should the compiler be?
2.7 Options for Debugging Your Program or GNU CC  Symbol tables, measurements, and debugging dumps.
2.8 Options That Control Optimization  How much optimization?
2.9 Options Controlling the Preprocessor  Controlling header files and macro definitions. Also, getting dependency information for Make.
2.10 Passing Options to the Assembler  Passing options to the assembler.
2.11 Options for Linking  Specifying libraries and so on.
2.12 Options for Directory Search  Where to find header files and libraries. Where to find the compiler executable files.
2.13 Specifying Target Machine and Compiler Version  Running a cross-compiler, or an old version of GNU CC.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.2 Options Controlling the Kind of Output

Compilation can involve up to four stages: preprocessing, compilation proper, assembly and linking, always in that order. The first three stages apply to an individual source file, and end by producing an object file; 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 library `libobjc.a' to make an Objective-C program work.

file.h
C header file (not to be compiled or linked).

file.cc
file.cxx
file.cpp
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.s
Assembler code.

file.S
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  objective-c  c++
c-header  cpp-output  c++-cpp-output
assembler  assembler-with-cpp

-x none
Turn off any specification of a language, so that subsequent files are handled according to their file name suffixes (as they are if `-x' has not been used at all).

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

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

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

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

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

Since only one output file can be specified, it does not make sense to use `-o' when compiling more than one input file, unless you are producing an executable file as output.

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

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

--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 -W option is also specified then command line options which have no documentation associated with them will also be displayed.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.3 Compiling C++ Programs

C++ source files conventionally use one of the suffixes `.C', `.cc', `.cpp', `.c++', `.cp', or `.cxx'; preprocessed C++ files use the suffix `.ii'. GNU CC 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, C++ programs often require class libraries as well as a compiler that understands the C++ language--and under some circumstances, you might want to compile programs from standard input, or otherwise without a suffix that flags them as C++ programs. g++ is a program that calls GNU CC with the default language set to C++, and automatically specifies linking against the C++ library. On many systems, the script 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. See section Options Controlling C Dialect, for explanations of options for languages related to C. See section Options Controlling C++ Dialect, for explanations of options that are meaningful only for C++ programs.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.4 Options Controlling C Dialect

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

-ansi
Support all ANSI standard C programs.

This turns off certain features of GNU C that are incompatible with ANSI C, such as the asm, inline 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 ANSI trigraph feature, and it disables recognition of C++ style `//' comments.

The alternate keywords __asm__, __extension__, __inline__ and __typeof__ continue to work despite `-ansi'. You would not want to use them in an ANSI 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-ANSI programs to be rejected gratuitously. For that, `-pedantic' is required in addition to `-ansi'. See section 2.6 Options to Request or Suppress Warnings.

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 ANSI standard doesn't call for; this is to avoid interfering with any programs that might use these names for other things.

The functions alloca, abort, exit, and _exit are not builtin functions when `-ansi' is used.

-flang-isoc9x
Enable support for features found in the C9X standard. In particular, enable support for the C9X restrict keyword.

Even when this option is not specified, you can still use some C9X features in so far as they do not conflict with previous C standards. For example, you may use __restrict__ even when -flang-isoc9x is not specified.

-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, as it also disables the other, C++-specific, extension keywords such as headof.

-fno-builtin
Don't recognize builtin functions that do not begin with `__builtin_' as prefix. Currently, the functions affected include abort, abs, alloca, cos, exit, fabs, ffs, labs, memcmp, memcpy, sin, sqrt, strcmp, strcpy, and strlen.

GCC normally generates special code to handle certain builtin 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.

The `-ansi' option prevents alloca and ffs from being builtin functions, since these functions do not have an ANSI standard meaning.

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

-trigraphs
Support ANSI C trigraphs. You don't want to know about this brain-damage. The `-ansi' option implies `-trigraphs'.

-traditional
Attempt to support some aspects of traditional C compilers. Specifically:

You may wish to use `-fno-builtin' as well as `-traditional' if your program uses names that are normally GNU C builtin functions for other purposes of its own.

You cannot use `-traditional' if you include any header files that rely on ANSI C features. Some vendors are starting to ship systems with ANSI C header files and you cannot use `-traditional' on such systems to compile files that include any system headers.

The `-traditional' option also enables `-traditional-cpp', which is described next.

-traditional-cpp
Attempt to support some aspects of traditional C preprocessors. Specifically:

-fcond-mismatch
Allow conditional expressions with mismatched types in the second and third arguments. The value of such an expression is void.

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

You may wish to use `-fno-builtin' as well as `-traditional' if your program uses names that are normally GNU C builtin functions for other purposes of its own.

You cannot use `-traditional' if you include any header files that rely on ANSI C features. Some vendors are starting to ship systems with ANSI C header files and you cannot use `-traditional' on such systems to compile files that include any system headers.

-fsigned-bitfields
-funsigned-bitfields
-fno-signed-bitfields
-fno-unsigned-bitfields
These options control whether a bitfield is signed or unsigned, when the declaration does not use either signed or unsigned. By default, such a bitfield is signed, because this is consistent: the basic integer types such as int are signed types.

However, when `-traditional' is used, bitfields are all unsigned no matter what.

-fwritable-strings
Store string constants in the writable data segment and don't uniquize them. This is for compatibility with old programs which assume they can write into string constants. The option `-traditional' also has this effect.

Writing into string constants is a very bad idea; "constants" should be constant.

-fallow-single-precision
Do not promote single precision math operations to double precision, even when compiling with `-traditional'.

Traditional K&R C promotes all floating point operations to double precision, regardless of the sizes of the operands. On the architecture for which you are compiling, single precision may be faster than double precision. If you must use `-traditional', but want to use single precision operations when the operands are single precision, use this option. This option has no effect when compiling with ANSI or GNU C conventions (the default).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.5 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 GNU CC.

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

-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. The current Working Paper requires that operator new never return a null pointer, so this check is normally unnecessary.

An alternative to using this option is to specify that your operator new does not throw any exceptions; if you declare it `throw()', g++ will check the return value. 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.

-fdollars-in-identifiers
Accept `$' in identifiers. You can also explicitly prohibit use of `$' with the option `-fno-dollars-in-identifiers'. (GNU C allows `$' by default on most target systems, but there are a few exceptions.) Traditional C allowed the character `$' to form part of identifiers. However, ANSI C and C++ forbid `$' in identifiers.

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

-fexternal-templates
Cause template instantiations to obey `#pragma interface' and `implementation'; template instances are emitted or not according to the location of the template definition. See section 4.5 Where's the Template?, for more information.

This option is deprecated.

-falt-external-templates
Similar to -fexternal-templates, but template instances are emitted or not according to the place where they are first instantiated. See section 4.5 Where's the Template?, for more information.

This option is deprecated.

-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 draft 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 gcc, 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 classof, headof, signature, sigof or typeof as a keyword, so that code can use these words as identifiers. You can use the keywords __classof__, __headof__, __signature__, __sigof__, and __typeof__ instead. `-ansi' implies `-fno-gnu-keywords'.

-fguiding-decls
Treat a function declaration with the same type as a potential function template instantiation as though it declares that instantiation, not a normal function. If a definition is given for the function later in the translation unit (or another translation unit if the target supports weak symbols), that definition will be used; otherwise the template will be instantiated. This behavior reflects the C++ language prior to September 1996, when guiding declarations were removed.

This option implies `-fname-mangling-version-0', and will not work with other name mangling versions. Like all options that change the ABI, all C++ code, including libgcc.a must be built with the same setting of this option.

-fhandle-signatures
Recognize the signature and sigof keywords for specifying abstract types. The default (`-fno-handle-signatures') is not to recognize them. See section Type Abstraction using Signatures.

-fhonor-std
Treat the namespace std as a namespace, instead of ignoring it. For compatibility with earlier versions of g++, the compiler will, by default, ignore namespace-declarations, using-declarations, using-directives, and namespace-names, if they involve std.

-fhuge-objects
Support virtual function calls for objects that exceed the size representable by a `short int'. Users should not use this flag by default; if you need to use it, the compiler will tell you so.

This flag is not useful when compiling with -fvtable-thunks.

Like all options that change the ABI, all C++ code, including libgcc must be built with the same setting of this option.

-fmerge-templates
Output templates and out-of-line copies of inline functions in special "linkonce sections". Each template is instantiated in every file that uses it; however duplicate sections are merged by the linker so that each template will appear exactly once in the output file. This avoids the "code bloat" associated with the default implicit instantiation method.

This flag is only supported on ELF targets.

-fno-implicit-templates
Never emit code for non-inline templates which are instantiated implicitly (i.e. by use); only emit code for explicit instantiations. See section 4.5 Where's the Template?, for more information.

-fno-implicit-inline-templates
Don't emit code for implicit instantiations of inline templates, either. The default is to handle inlines differently so that compiles with and without optimization will need the same set of explicit instantiations.

-finit-priority
Support `__attribute__ ((init_priority (n)))' for controlling the order of initialization of file-scope objects. On ELF targets, this requires GNU ld 2.10 or later.

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

-fname-mangling-version-n
Control the way in which names are mangled. Version 0 is compatible with versions of g++ before 2.8. Version 1 is the default. Version 1 will allow correct mangling of function templates. For example, version 0 mangling does not mangle foo<int, double> and foo<int, char> given this declaration:

 
template <class T, class U> void foo(T t);

Like all options that change the ABI, all C++ code, including libgcc must be built with the same setting of this option.

-foperator-names
Recognize the operator name keywords and, bitand, bitor, compl, not, or and xor as synonyms for the symbols they refer to. `-ansi' implies `-foperator-names'.

-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 messages about nonconformant code from errors to warnings. By default, g++ effectively sets `-pedantic-errors' without `-pedantic'; this option reverses that. This behavior and this option are superceded by `-pedantic', which works as it does for GNU C.

-frepo
Enable automatic template instantiation. This option also implies `-fno-implicit-templates'. See section 4.5 Where's the Template?, for more information.

-fno-rtti
Disable generation of the information used by C++ runtime type identification features (`dynamic_cast' and `typeid'). If you don't use those parts of the language (or exception handling, which uses `dynamic_cast' internally), you can save some space by using this flag.

-fstrict-prototype
Within an `extern "C"' linkage specification, treat a function declaration with no arguments, such as `int foo ();', as declaring the function to take no arguments. Normally, such a declaration means that the function foo can take any combination of arguments, as in C. `-pedantic' implies `-fstrict-prototype' unless overridden with `-fno-strict-prototype'.

Specifying this option will also suppress implicit declarations of functions.

This flag no longer affects declarations with C++ linkage.

-fsquangle
-fno-squangle
`-fsquangle' will enable a compressed form of name mangling for identifiers. In particular, it helps to shorten very long names by recognizing types and class names which occur more than once, replacing them with special short ID codes. This option also requires any C++ libraries being used to be compiled with this option as well. The compiler has this disabled (the equivalent of `-fno-squangle') by default.

Like all options that change the ABI, all C++ code, including libgcc.a must be built with the same setting of this option.

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

-fthis-is-variable
Permit assignment to this. The incorporation of user-defined free store management into C++ has made assignment to `this' an anachronism. Therefore, by default it is invalid to assign to this within a class member function; that is, GNU C++ treats `this' in a member function of class X as a non-lvalue of type `X *'. However, for backwards compatibility, you can make it valid with `-fthis-is-variable'.

-fvtable-thunks
Use `thunks' to implement the virtual function dispatch table (`vtable'). The traditional (cfront-style) approach to implementing vtables was to store a pointer to the function and two offsets for adjusting the `this' pointer at the call site. Newer implementations store a single pointer to a `thunk' function which does any necessary adjustment and then calls the target function.

This option also enables a heuristic for controlling emission of vtables; if a class has any non-inline virtual functions, the vtable will be emitted in the translation unit containing the first one of those.

Like all options that change the ABI, all C++ code, including libgcc.a must be built with the same setting of this option.

-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. See section Options That Control Optimization. Note that these functions will have linkage like inline functions; they just won't be inlined by default.

-Wctor-dtor-privacy (C++ only)
Warn when a class seems unusable, because all the constructors or destructors in a class are private and the class has no friends or public static member functions.

-Wnon-virtual-dtor (C++ only)
Warn when a class declares a non-virtual destructor that should probably be virtual, because it looks like the class will be used polymorphically.

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

Here the compiler will warn that the member initializers for `i' and `j' will be rearranged to match the declaration order of the members.

The following `-W...' options are not affected by `-Wall'.

-Weffc++ (C++ only)
Warn about violations of various style guidelines from Scott Meyers' Effective C++ books. If you use this option, you should be aware that the standard library headers do not obey all of these guidelines; you can use `grep -v' to filter out those warnings.

-Wno-deprecated (C++ only)
Do not warn about usage of deprecated features. See section 3.40 Deprecated Features.

-Wno-non-template-friend (C++ only)
Disable warnings when non-templatized friend functions are declared within a template. With the advent of explicit template specification support in g++, if the name of the friend is an unqualified-id (ie, `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 also be turned off with the flag `-fguiding-decls', which activates the older, non-specification compiler code, or with `-Wno-non-template-friend' which keeps the conformant compiler code but disables the helpful warning.

-Wold-style-cast (C++ only)
Warn if an old-style (C-style) cast is used within a C++ program. The new-style casts (`static_cast', `reinterpret_cast', and `const_cast') are less vulnerable to unintended effects.

-Woverloaded-virtual (C++ only)
Warn when a derived class function declaration may be an error in defining a virtual function. In a derived class, the definitions of virtual functions must match the type signature of a virtual function declared in the base class. With this option, the compiler warns when you define a function with the same name as a virtual function, but with a type signature that does not match any declarations from the base class.

-Wno-pmf-conversions (C++ only)
Disable the diagnostic for converting a bound pointer to member function to a plain pointer.

-Wsign-promo (C++ only)
Warn when overload resolution chooses a promotion from unsigned or enumeral 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.

-Wsynth (C++ only)
Warn when g++'s synthesis behavior does not match that of cfront. For instance:

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


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

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

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.

These options control the amount and kinds of warnings produced by GNU CC:

-fsyntax-only
Check the code for syntax errors, but don't do anything beyond that.

-pedantic
Issue all the warnings demanded by strict ANSI C and ISO C++; reject all programs that use forbidden extensions.

Valid ANSI C and ISO C++ programs should compile properly with or without this option (though a rare few will require `-ansi'). 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. See section 3.35 Alternate Keywords.

This option is not intended to be useful; it exists only to satisfy pedants who would otherwise claim that GNU CC fails to support the ANSI standard.

Some users try to use `-pedantic' to check programs for strict ANSI C conformance. They soon find that it does not do quite what they want: it finds some non-ANSI practices, but not all--only those for which ANSI C requires a diagnostic.

A feature to report any failure to conform to ANSI 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.

-pedantic-errors
Like `-pedantic', except that errors are produced rather than warnings.

-w
Inhibit all warning messages.

-Wno-import
Inhibit warning messages about the use of `#import'.

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

-Wcomment
Warn whenever a comment-start sequence `/*' appears in a `/*' comment, or whenever a Backslash-Newline appears in a `//' comment.

-Wformat
Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified.

-Wimplicit-int
Warn when a declaration does not specify a type.

-Wimplicit-function-declaration
-Werror-implicit-function-declaration
Give a warning (or error) whenever a function is used before being declared.

-Wimplicit
Same as `-Wimplicit-int' and `-Wimplicit-function-'
`declaration'.

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

-Wmultichar
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.
-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 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, 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, GNU C 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 ();
    }
}

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

-Wswitch
Warn whenever a switch statement has an index of enumeral type and lacks a case for one or more of the named codes of that enumeration. (The presence of a default label prevents this warning.) case labels outside the enumeration range also provoke warnings when this option is used.

-Wtrigraphs
Warn if any trigraphs are encountered (assuming they are enabled).

-Wunused
Warn whenever a variable is unused aside from its declaration, whenever a function is declared static but never defined, whenever a label is declared but not used, and whenever a statement computes a result that is explicitly not used.

In order to get a warning about an unused function parameter, you must specify both `-W' and `-Wunused'.

To suppress this warning for an expression, simply cast it to void. For unused variables, parameters and labels, use the `unused' attribute (see section 3.29 Specifying Attributes of Variables).

-Wuninitialized
An automatic variable is used without first being initialized.

These warnings are possible only in optimizing compilation, because they require data flow information that is computed only when optimizing. If you don't specify `-O', you simply won't get these warnings.

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

Note that there may be no warning about a variable that is used only to compute a value that itself is never used, because such computations may be deleted by data flow analysis before the warnings are printed.

These warnings are made optional because GNU CC 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 GNU CC 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.

Some spurious warnings can be avoided if you declare all the functions you use that never return as noreturn. See section 3.23 Declaring Attributes of Functions.

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

-Wall
All of the above `-W' options combined. 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.

The following `-W...' options 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.

-W
Print extra warning messages for these events:

-Wtraditional
Warn about certain constructs that behave differently in traditional and ANSI C.

-Wundef
Warn if an undefined identifier is evaluated in an `#if' directive.

-Wshadow
Warn whenever a local variable shadows another local variable.

-Wid-clash-len
Warn whenever two distinct identifiers match in the first len characters. This may help you prepare a program that will compile with certain obsolete, brain-damaged compilers.

-Wlarger-than-len
Warn whenever an object of larger than len bytes is defined.

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

-Wbad-function-cast
Warn whenever a function call is cast to a non-matching type. For example, warn if int malloc() is cast to anything *.

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

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

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

-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 `-W'; to get the other warnings of `-W' without this warning, use `-W -Wno-sign-compare'.

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

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

-Wmissing-prototypes
Warn if a global function is defined without a previous prototype declaration. This warning is issued even if the definition itself provides a prototype. The aim is to detect global functions that 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.

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

-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
Warn if an extern declaration is encountered within an function.

-Winline
Warn if a function can not be inlined, and either it was declared as inline, or else the `-finline-functions' option was given.

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

-Werror
Make all warnings into errors.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.7 Options for Debugging Your Program or GNU CC

GNU CC 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). 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', `-gdwarf-1+', or `-gdwarf-1' (see below).

Unlike most other C compilers, GNU CC 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 GNU CC 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.

-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
Produce debugging information in DWARF version 1 format (if that is supported). This is the format used by SDB on most System V Release 4 systems.

-gdwarf+
Produce debugging information in DWARF version 1 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.

-gdwarf-2
Produce debugging information in DWARF version 2 format (if that is supported). This is the format used by DBX on IRIX 6.

-glevel
-ggdblevel
-gstabslevel
-gcofflevel
-gxcofflevel
-gdwarflevel
-gdwarf-2level
Request debugging information and also use level to specify how much information. The default level is 2.

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

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

-a
Generate extra code to write profile information for basic blocks, which will record the number of times each basic block is executed, the basic block start address, and the function name containing the basic block. If `-g' is used, the line number and filename of the start of the basic block will also be recorded. If not overridden by the machine description, the default action is to append to the text file `bb.out'.

This data could be analyzed by a program like tcov. Note, however, that the format of the data is not what tcov expects. Eventually GNU gprof should be extended to process this data.

-Q
Makes the compiler print out each function name as it is compiled, and print some statistics about each pass when it finishes.

-ax
Generate extra code to profile basic blocks. Your executable will produce output that is a superset of that produced when `-a' is used. Additional output is the source and target address of the basic blocks where a jump takes place, the number of times a jump is executed, and (optionally) the complete sequence of basic blocks being executed. The output is appended to file `bb.out'.

You can examine different profiling aspects without recompilation. Your executable will read a list of function names from file `bb.in'. Profiling starts when a function on the list is entered and stops when that invocation is exited. To exclude a function from profiling, prefix its name with `-'. If a function name is not unique, you can disambiguate it by writing it in the form `/path/filename.d:functionname'. Your executable will write the available paths and filenames in file `bb.out'.

Several function names have a special meaning:

__bb_jumps__
Write source, target and frequency of jumps to file `bb.out'.
__bb_hidecall__
Exclude function calls from frequency count.
__bb_showret__
Include function returns in frequency count.
__bb_trace__
Write the sequence of basic blocks executed to file `bbtrace.gz'. The file will be compressed using the program `gzip', which must exist in your PATH. On systems without the `popen' function, the file will be named `bbtrace' and will not be compressed. Profiling for even a few seconds on these systems will produce a very large file. Note: __bb_hidecall__ and __bb_showret__ will not affect the sequence written to `bbtrace.gz'.

Here's a short example using different profiling parameters in file `bb.in'. Assume function foo consists of basic blocks 1 and 2 and is called twice from block 3 of function main. After the calls, block 3 transfers control to block 4 of main.

With __bb_trace__ and main contained in file `bb.in', the following sequence of blocks is written to file `bbtrace.gz': 0 3 1 2 1 2 4. The return from block 2 to block 3 is not shown, because the return is to a point inside the block and not to the top. The block address 0 always indicates, that control is transferred to the trace from somewhere outside the observed functions. With `-foo' added to `bb.in', the blocks of function foo are removed from the trace, so only 0 3 4 remains.

With __bb_jumps__ and main contained in file `bb.in', jump frequencies will be written to file `bb.out'. The frequencies are obtained by constructing a trace of blocks and incrementing a counter for every neighbouring pair of blocks in the trace. The trace 0 3 1 2 1 2 4 displays the following frequencies:

 
Jump from block 0x0 to block 0x3 executed 1 time(s)
Jump from block 0x3 to block 0x1 executed 1 time(s)
Jump from block 0x1 to block 0x2 executed 2 time(s)
Jump from block 0x2 to block 0x1 executed 1 time(s)
Jump from block 0x2 to block 0x4 executed 1 time(s)

With __bb_hidecall__, control transfer due to call instructions is removed from the trace, that is the trace is cut into three parts: 0 3 4, 0 1 2 and 0 1 2. With __bb_showret__, control transfer due to return instructions is added to the trace. The trace becomes: 0 3 1 2 3 1 2 3 4. Note, that this trace is not the same, as the sequence written to `bbtrace.gz'. It is solely used for counting jump frequencies.

-fprofile-arcs
Instrument arcs during compilation. For each function of your program, GNU CC 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.

Since not every arc in the program must be instrumented, programs compiled with this option run faster than programs compiled with `-a', which adds instrumentation code to every basic block in the program. The tradeoff: since gcov does not have execution counts for all branches, it must start with the execution counts for the instrumented branches, and then iterate over the program flow graph until the entire graph has been solved. Hence, gcov runs a little more slowly than a program which uses information from `-a'.

`-fprofile-arcs' also makes it possible to estimate branch probabilities, and to calculate basic block execution counts. In general, basic block execution counts do not give enough information to estimate all branch probabilities. When the compiled program exits, it saves the arc execution counts to a file called `sourcename.da'. Use the compiler option `-fbranch-probabilities' (see section Options that Control Optimization) when recompiling, to optimize using estimated branch probabilities.

-ftest-coverage
Create data files for the gcov code-coverage utility. The data file names begin with the name of your source file:

sourcename.bb
A mapping from basic blocks to line numbers, which gcov uses to associate basic block execution counts with line numbers.

sourcename.bbg
A list of all arcs in the program flow graph. This allows gcov to reconstruct the program flow graph, so that it can compute all basic block and arc execution counts from the information in the sourcename.da file (this last file is the output from `-fprofile-arcs').

-Q
Makes the compiler print out each function name as it is compiled, and print some statistics about each pass when it finishes.

-dletters
Says to make debugging dumps during compilation at times specified by letters. This is used for debugging the compiler. The file names for most of the dumps are made by appending a word to the source file name (e.g. `foo.c.rtl' or `foo.c.jump'). Here are the possible letters for use in letters, and their meanings:

`b'
Dump after computing branch probabilities, to `file.bp'.
`c'
Dump after instruction combination, to the file `file.combine'.
`d'
Dump after delayed branch scheduling, to `file.dbr'.
`D'
Dump all macro definitions, at the end of preprocessing, in addition to normal output.
`r'
Dump after RTL generation, to `file.rtl'.
`j'
Dump after first jump optimization, to `file.jump'.
`F'
Dump after purging ADDRESSOF, to `file.addressof'.
`f'
Dump after flow analysis, to `file.flow'.
`g'
Dump after global register allocation, to `file.greg'.
`G'
Dump after GCSE, to `file.gcse'.
`j'
Dump after first jump optimization, to `file.jump'.
`J'
Dump after last jump optimization, to `file.jump2'.
`k'
Dump after conversion from registers to stack, to `file.stack'.
`l'
Dump after local register allocation, to `file.lreg'.
`L'
Dump after loop optimization, to `file.loop'.
`M'
Dump after performing the machine dependent reorganisation pass, to `file.mach'.
`N'
Dump after the register move pass, to `file.regmove'.
`r'
Dump after RTL generation, to `file.rtl'.
`R'
Dump after the second instruction scheduling pass, to `file.sched2'.
`s'
Dump after CSE (including the jump optimization that sometimes follows CSE), to `file.cse'.
`S'
Dump after the first instruction scheduling pass, to `file.sched'.
`t'
Dump after the second CSE pass (including the jump optimization that sometimes follows CSE), to `file.cse2'.
`a'
Produce all the dumps listed above.
`m'
Print statistics on memory usage, at the end of the run, to standard error.
`p'
Annotate the assembler output with a comment indicating which pattern and alternative was used. The length of each instruction is also printed.
`x'
Just generate RTL for a function instead of compiling it. Usually used with `r'.
`y'
Dump debugging information during parsing, to standard error.
`A'
Annotate the assembler output with miscellaneous debugging information.

-fdump-unnumbered
When doing debugging dumps (see -d option above), suppress instruction numbers and line number note output. This makes it more feasible to use diff on debugging dumps for compiler invokations with different options, in particular with and without -g.

-fpretend-float
When running a cross-compiler, pretend that the target machine uses the same floating point format as the host machine. This causes incorrect output of the actual floating constants, but the actual instruction sequence will probably be the same as GNU CC would make when running on the target machine.

-save-temps
Store the usual "temporary" intermediate files permanently; place them in the current directory and name them based on the source file. Thus, compiling `foo.c' with `-c -save-temps' would produce files `foo.i' and `foo.s', as well as `foo.o'.

-print-file-name=library
Print the full absolute name of the library file library that would be used when linking--and don't do anything else. With this option, GNU CC does not compile or link anything; it just prints the file name.

-print-prog-name=program
Like `-print-file-name', but searches for a program such as `cpp'.

-print-libgcc-file-name
Same as `-print-file-name=libgcc.a'.

This is useful when you use `-nostdlib' or `-nodefaultlibs' but you do want to link with `libgcc.a'. You can do

 
gcc -nostdlib files... `gcc -print-libgcc-file-name`

-print-search-dirs
Print the name of the configured installation directory and a list of program and library directories gcc will search--and don't do anything else.

This is useful when gcc prints the error message `installation problem, cannot exec cpp: No such file or directory'. To resolve this you either need to put `cpp' and the other compiler components where gcc expects to find them.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.8 Options That Control Optimization

These options control various sorts of optimizations:

-O
-O1
Optimize. Optimizing compilation takes somewhat more time, and a lot more memory for a large function.

Without `-O', the compiler's goal is to reduce the cost of compilation and to make debugging produce the expected results. Statements are independent: if you stop the program with a breakpoint between statements, you can then assign a new value to any variable or change the program counter to any other statement in the function and get exactly the results you would expect from the source code.

Without `-O', the compiler only allocates variables declared register in registers. The resulting compiled code is a little worse than produced by PCC without `-O'.

With `-O', the compiler tries to reduce code size and execution time.

When you specify `-O', the compiler turns on `-fthread-jumps' and `-fdefer-pop' on all machines. The compiler turns on `-fdelayed-branch' on machines that have delay slots, and `-fomit-frame-pointer' on machines that can support debugging even without a frame pointer. On some machines the compiler also turns on other flags.

-O2
Optimize even more. GNU CC performs nearly all supported optimizations that do not involve a space-speed tradeoff. The compiler does not perform loop unrolling or function inlining when you specify `-O2'. As compared to `-O', this option increases both compilation time and the performance of the generated code.

`-O2' turns on all optional optimizations except for loop unrolling and function inlining. It also turns on the `-fforce-mem' option on all machines and frame pointer elimination on machines where doing so does not interfere with debugging.

-O3
Optimize yet more. `-O3' turns on all optimizations specified by `-O2' and also turns on the `inline-functions' option.

-O0
Do not optimize.

-Os
Optimize for size. `-Os' enables all `-O2' optimizations that do not typically increase code size. It also performs further optimizations designed to reduce code size.

If you use multiple `-O' options, with or without level numbers, the last such option is the one that is effective.

Options of the form `-fflag' specify machine-independent flags. Most flags have both positive and negative forms; the negative form of `-ffoo' would be `-fno-foo'. In the table below, only one of the forms is listed--the one which is not the default. You can figure out the other form by either removing `no-' or adding it.

-ffloat-store
Do not store floating point variables in registers, and inhibit other options that might change whether a floating point value is taken from a register or memory.

This option prevents undesirable excess precision on machines such as the 68000 where the floating registers (of the 68881) keep more precision than a double is supposed to have. Similarly for the x86 architecture. For most programs, the excess precision does only good, but a few programs rely on the precise definition of IEEE floating point. Use `-ffloat-store' for such programs, after modifying them to store all pertinent intermediate computations into variables.

-fno-default-inline
Do not make member functions inline by default merely because they are defined inside the class scope (C++ only). Otherwise, when you specify `-O', member functions defined inside class scope are compiled inline by default; i.e., you don't need to add `inline' in front of the member function name.

-fno-defer-pop
Always pop the arguments to each function call as soon as that function returns. For machines which must pop arguments after a function call, the compiler normally lets arguments accumulate on the stack for several function calls and pops them all at once.

-fforce-mem
Force memory operands to be copied into registers before doing arithmetic on them. This produces better code by making all memory references potential common subexpressions. When they are not common subexpressions, instruction combination should eliminate the separate register-load. The `-O2' option turns on this option.

-fforce-addr
Force memory address constants to be copied into registers before doing arithmetic on them. This may produce better code just as `-fforce-mem' may.

-fomit-frame-pointer
Don't keep the frame pointer in a register for functions that don't need one. This avoids the instructions to save, set up and restore frame pointers; it also makes an extra register available in many functions. It also makes debugging impossible on some machines.

On some machines, such as the Vax, this flag has no effect, because the standard calling sequence automatically handles the frame pointer and nothing is saved by pretending it doesn't exist. The machine-description macro FRAME_POINTER_REQUIRED controls whether a target machine supports this flag. See section `Register Usage' in Using and Porting GCC.

-fno-inline
Don't pay attention to the inline keyword. Normally this option is used to keep the compiler from expanding any functions inline. Note that if you are not optimizing, no functions can be expanded inline.

-finline-functions
Integrate all simple functions into their callers. The compiler heuristically decides which functions are simple enough to be worth integrating in this way.

If all calls to a given function are integrated, and the function is declared static, then the function is normally not output as assembler code in its own right.

-finline-limit-n
By default, gcc limits the size of functions that can be inlined. This flag allows the control of this limit for functions that are explicitly marked as inline (ie marked with the inline keyword or defined within the class definition in c++). n is the size of functions that can be inlined in number of pseudo instructions (not counting parameter handling). The default value of n is 10000. Increasing this value can result in more inlined code at the cost of compilation time and memory consumption. Decreasing usually makes the compilation faster and less code will be inlined (which presumably means slower programs). This option is particularly useful for programs that use inlining heavily such as those based on recursive templates with c++.

Note: pseudo instruction represents, in this particular context, an abstract measurement of function's size. In no way, it represents a count of assembly instructions and as such its exact meaning might change from one release to an another.

-fkeep-inline-functions
Even if all calls to a given function are integrated, and the function is declared static, nevertheless output a separate run-time callable version of the function. This switch does not affect extern inline functions.

-fkeep-static-consts
Emit variables declared static const when optimization isn't turned on, even if the variables aren't referenced.

GNU CC enables this option by default. If you want to force the compiler to check if the variable was referenced, regardless of whether or not optimization is turned on, use the `-fno-keep-static-consts' option.

-fno-function-cse
Do not put function addresses in registers; make each instruction that calls a constant function contain the function's address explicitly.

This option results in less efficient code, but some strange hacks that alter the assembler output may be confused by the optimizations performed when this option is not used.

-ffast-math
This option allows GCC to violate some ANSI or IEEE rules and/or specifications in the interest of optimizing code for speed. For example, it allows the compiler to assume arguments to the sqrt function are non-negative numbers and that no floating-point values are NaNs.

This option should never be turned on by any `-O' option since it can result in incorrect output for programs which depend on an exact implementation of IEEE or ANSI rules/specifications for math functions.

The following options control specific optimizations. The `-O2' option turns on all of these optimizations except `-funroll-loops' and `-funroll-all-loops'. On most machines, the `-O' option turns on the `-fthread-jumps' and `-fdelayed-branch' options, but specific machines may handle it differently.

You can use the following flags in the rare cases when "fine-tuning" of optimizations to be performed is desired.

-fstrength-reduce
Perform the optimizations of loop strength reduction and elimination of iteration variables.

-fthread-jumps
Perform optimizations where we check to see if a jump branches to a location where another comparison subsumed by the first is found. If so, the first branch is redirected to either the destination of the second branch or a point immediately following it, depending on whether the condition is known to be true or false.

-fcse-follow-jumps
In common subexpression elimination, scan through jump instructions when the target of the jump is not reached by any other path. For example, when CSE encounters an if statement with an else clause, CSE will follow the jump when the condition tested is false.

-fcse-skip-blocks
This is similar to `-fcse-follow-jumps', but causes CSE to follow jumps which conditionally skip over blocks. When CSE encounters a simple if statement with no else clause, `-fcse-skip-blocks' causes CSE to follow the jump around the body of the if.

-frerun-cse-after-loop
Re-run common subexpression elimination after loop optimizations has been performed.

-frerun-loop-opt
Run the loop optimizer twice.

-fgcse
Perform a global common subexpression elimination pass. This pass also performs global constant and copy propagation.

-fexpensive-optimizations
Perform a number of minor optimizations that are relatively expensive.

-foptimize-register-moves
-fregmove
Attempt to reassign register numbers in move instructions and as operands of other simple instructions in order to maximize the amount of register tying. This is especially helpful on machines with two-operand instructions. GNU CC enables this optimization by default with `-O2' or higher.

Note -fregmove and -foptimize-register-moves are the same optimization.

-fdelayed-branch
If supported for the target machine, attempt to reorder instructions to exploit instruction slots available after delayed branch instructions.

-fschedule-insns
If supported for the target machine, attempt to reorder instructions to eliminate execution stalls due to required data being unavailable. This helps machines that have slow floating point or memory load instructions by allowing other instructions to be issued until the result of the load or floating point instruction is required.

-fschedule-insns2
Similar to `-fschedule-insns', but requests an additional pass of instruction scheduling after register allocation has been done. This is especially useful on machines with a relatively small number of registers and where memory load instructions take more than one cycle.

-ffunction-sections
-fdata-sections
Place each function or data item into its own section in the output file if the target supports arbitrary sections. The name of the function or the name of the data item determines the section's name in the output file.

Use these options on systems where the linker can perform optimizations to improve locality of reference in the instruction space. HPPA processors running HP-UX and Sparc processors running Solaris 2 have linkers with such optimizations. Other systems using the ELF object format as well as AIX may have these optimizations in the future.

Only use these options when there are significant benefits from doing so. When you specify these options, the assembler and linker will create larger object and executable files and will also be slower. You will not be able to use gprof on all systems if you specify this option and you may have problems with debugging if you specify both this option and `-g'.

-fcaller-saves
Enable values to be allocated in registers that will be clobbered by function calls, by emitting extra instructions to save and restore the registers around such calls. Such allocation is done only when it seems to result in better code than would otherwise be produced.

This option is always enabled by default on certain machines, usually those which have no call-preserved registers to use instead.

For all machines, optimization level 2 and higher enables this flag by default.

-funroll-loops
Perform the optimization of loop unrolling. This is only done for loops whose number of iterations can be determined at compile time or run time. `-funroll-loop' implies both `-fstrength-reduce' and `-frerun-cse-after-loop'.

-funroll-all-loops
Perform the optimization of loop unrolling. This is done for all loops and usually makes programs run more slowly. `-funroll-all-loops' implies `-fstrength-reduce' as well as `-frerun-cse-after-loop'.

-fmove-all-movables
Forces all invariant computations in loops to be moved outside the loop.

-freduce-all-givs
Forces all general-induction variables in loops to be strength-reduced.

Note: When compiling programs written in Fortran, `-fmove-all-moveables' and `-freduce-all-givs' are enabled by default when you use the optimizer.

These options may generate better or worse code; results are highly dependent on the structure of loops within the source code.

These two options are intended to be removed someday, once they have helped determine the efficacy of various approaches to improving loop optimizations.

Please let us (egcs@egcs.cygnus.com and fortran@gnu.org) know how use of these options affects the performance of your production code. We're very interested in code that runs slower when these options are enabled.

-fno-peephole
Disable any machine-specific peephole optimizations.

-fbranch-probabilities
After running a program compiled with `-fprofile-arcs' (see section Options for Debugging Your Program or gcc), you can compile it a second time using `-fbranch-probabilities', to improve optimizations based on guessing the path a branch might take.

-fstrict-aliasing
Allows the compiler to assume the strictest aliasing rules applicable to the language being compiled. For C (and C++), this activates optimizations based on the type of expressions. In particular, an object of one type is assumed never to reside at the same address as an object of a different type, unless the types are almost the same. For example, an unsigned int can alias an int, but not a void* or a double. A character type may alias any other type.

Pay special attention to code like this:
 
union a_union { 
  int i;
  double d;
};

int f() {
  a_union t;
  t.d = 3.0;
  return t.i;
}
The practice of reading from a different union member than the one most recently written to (called "type-punning") is common. Even with `-fstrict-aliasing', type-punning is allowed, provided the memory is accessed through the union type. So, the code above will work as expected. However, this code might not:
 
int f() { 
  a_union t;
  int* ip;
  t.d = 3.0;
  ip = &t.i;
  return *ip;
}


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9 Options Controlling the Preprocessor

These options control the C preprocessor, which is run on each C source file before actual compilation.

If you use the `-E' option, nothing is done except preprocessing. Some of these options make sense only together with `-E' because they cause the preprocessor output to be unsuitable