GCC(1) | GNU | GCC(1) |
gcc - GNU project C and C++ compiler
gcc [-c|-S|-E] [-std=standard]
[-g] [-pg] [-Olevel]
[-Wwarn...] [-Wpedantic]
[-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.
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 or more stages 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 usual way to run GCC is to run the executable called gcc, or machine-gcc when cross-compiling, or machine-gcc-version to run a specific version of GCC. When you compile C++ programs, you should invoke GCC as g++ instead.
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 is -fno-foo. This manual documents only one of these two forms, whichever one is not the default.
Here is a summary of all the options, grouped by type. Explanations are in the following sections.
Adapteva Epiphany Options -mhalf-reg-file -mprefer-short-insn-regs -mbranch-cost=num -mcmove -mnops=num -msoft-cmpsf -msplit-lohi -mpost-inc -mpost-modify -mstack-offset=num -mround-nearest -mlong-calls -mshort-calls -msmall16 -mfp-mode=mode -mvect-double -max-vect-align=num -msplit-vecmove-early -m1reg-reg
ARC Options -mbarrel-shifter -mcpu=cpu -mA6 -mARC600 -mA7 -mARC700 -mdpfp -mdpfp-compact -mdpfp-fast -mno-dpfp-lrsr -mea -mno-mpy -mmul32x16 -mmul64 -matomic -mnorm -mspfp -mspfp-compact -mspfp-fast -msimd -msoft-float -mswap -mcrc -mdsp-packa -mdvbf -mlock -mmac-d16 -mmac-24 -mrtsc -mswape -mtelephony -mxy -misize -mannotate-align -marclinux -marclinux_prof -mlong-calls -mmedium-calls -msdata -mvolatile-cache -mtp-regno=regno -malign-call -mauto-modify-reg -mbbit-peephole -mno-brcc -mcase-vector-pcrel -mcompact-casesi -mno-cond-exec -mearly-cbranchsi -mexpand-adddi -mindexed-loads -mlra -mlra-priority-none -mlra-priority-compact mlra-priority-noncompact -mno-millicode -mmixed-code -mq-class -mRcq -mRcw -msize-level=level -mtune=cpu -mmultcost=num -munalign-prob-threshold=probability -mmpy-option=multo -mdiv-rem -mcode-density -mll64 -mfpu=fpu
ARM Options -mapcs-frame -mno-apcs-frame -mabi=name -mapcs-stack-check -mno-apcs-stack-check -mapcs-reentrant -mno-apcs-reentrant -msched-prolog -mno-sched-prolog -mlittle-endian -mbig-endian -mfloat-abi=name -mfp16-format=name -mthumb-interwork -mno-thumb-interwork -mcpu=name -march=name -mfpu=name -mtune=name -mprint-tune-info -mstructure-size-boundary=n -mabort-on-noreturn -mlong-calls -mno-long-calls -msingle-pic-base -mno-single-pic-base -mpic-register=reg -mnop-fun-dllimport -mpoke-function-name -mthumb -marm -mtpcs-frame -mtpcs-leaf-frame -mcaller-super-interworking -mcallee-super-interworking -mtp=name -mtls-dialect=dialect -mword-relocations -mfix-cortex-m3-ldrd -munaligned-access -mneon-for-64bits -mslow-flash-data -masm-syntax-unified -mrestrict-it -mpure-code -mcmse
AVR Options -mmcu=mcu -mabsdata -maccumulate-args -mbranch-cost=cost -mcall-prologues -mint8 -mn_flash=size -mno-interrupts -mrelax -mrmw -mstrict-X -mtiny-stack -mfract-convert-truncate -nodevicelib -Waddr-space-convert -Wmisspelled-isr
Blackfin Options -mcpu=cpu[-sirevision] -msim -momit-leaf-frame-pointer -mno-omit-leaf-frame-pointer -mspecld-anomaly -mno-specld-anomaly -mcsync-anomaly -mno-csync-anomaly -mlow-64k -mno-low64k -mstack-check-l1 -mid-shared-library -mno-id-shared-library -mshared-library-id=n -mleaf-id-shared-library -mno-leaf-id-shared-library -msep-data -mno-sep-data -mlong-calls -mno-long-calls -mfast-fp -minline-plt -mmulticore -mcorea -mcoreb -msdram -micplb
C6X Options -mbig-endian -mlittle-endian -march=cpu -msim -msdata=sdata-type
CRIS Options -mcpu=cpu -march=cpu -mtune=cpu -mmax-stack-frame=n -melinux-stacksize=n -metrax4 -metrax100 -mpdebug -mcc-init -mno-side-effects -mstack-align -mdata-align -mconst-align -m32-bit -m16-bit -m8-bit -mno-prologue-epilogue -mno-gotplt -melf -maout -melinux -mlinux -sim -sim2 -mmul-bug-workaround -mno-mul-bug-workaround
CR16 Options -mmac -mcr16cplus -mcr16c -msim -mint32 -mbit-ops -mdata-model=model
Darwin Options -all_load -allowable_client -arch -arch_errors_fatal -arch_only -bind_at_load -bundle -bundle_loader -client_name -compatibility_version -current_version -dead_strip -dependency-file -dylib_file -dylinker_install_name -dynamic -dynamiclib -exported_symbols_list -filelist -flat_namespace -force_cpusubtype_ALL -force_flat_namespace -headerpad_max_install_names -iframework -image_base -init -install_name -keep_private_externs -multi_module -multiply_defined -multiply_defined_unused -noall_load -no_dead_strip_inits_and_terms -nofixprebinding -nomultidefs -noprebind -noseglinkedit -pagezero_size -prebind -prebind_all_twolevel_modules -private_bundle -read_only_relocs -sectalign -sectobjectsymbols -whyload -seg1addr -sectcreate -sectobjectsymbols -sectorder -segaddr -segs_read_only_addr -segs_read_write_addr -seg_addr_table -seg_addr_table_filename -seglinkedit -segprot -segs_read_only_addr -segs_read_write_addr -single_module -static -sub_library -sub_umbrella -twolevel_namespace -umbrella -undefined -unexported_symbols_list -weak_reference_mismatches -whatsloaded -F -gused -gfull -mmacosx-version-min=version -mkernel -mone-byte-bool
DEC Alpha Options -mno-fp-regs -msoft-float -mieee -mieee-with-inexact -mieee-conformant -mfp-trap-mode=mode -mfp-rounding-mode=mode -mtrap-precision=mode -mbuild-constants -mcpu=cpu-type -mtune=cpu-type -mbwx -mmax -mfix -mcix -mfloat-vax -mfloat-ieee -mexplicit-relocs -msmall-data -mlarge-data -msmall-text -mlarge-text -mmemory-latency=time
FR30 Options -msmall-model -mno-lsim
FT32 Options -msim -mlra -mnodiv
FRV Options -mgpr-32 -mgpr-64 -mfpr-32 -mfpr-64 -mhard-float -msoft-float -malloc-cc -mfixed-cc -mdword -mno-dword -mdouble -mno-double -mmedia -mno-media -mmuladd -mno-muladd -mfdpic -minline-plt -mgprel-ro -multilib-library-pic -mlinked-fp -mlong-calls -malign-labels -mlibrary-pic -macc-4 -macc-8 -mpack -mno-pack -mno-eflags -mcond-move -mno-cond-move -moptimize-membar -mno-optimize-membar -mscc -mno-scc -mcond-exec -mno-cond-exec -mvliw-branch -mno-vliw-branch -mmulti-cond-exec -mno-multi-cond-exec -mnested-cond-exec -mno-nested-cond-exec -mtomcat-stats -mTLS -mtls -mcpu=cpu
GNU/Linux Options -mglibc -muclibc -mmusl -mbionic -mandroid -tno-android-cc -tno-android-ld
H8/300 Options -mrelax -mh -ms -mn -mexr -mno-exr -mint32 -malign-300
HPPA Options -march=architecture-type -mcaller-copies -mdisable-fpregs -mdisable-indexing -mfast-indirect-calls -mgas -mgnu-ld -mhp-ld -mfixed-range=register-range -mjump-in-delay -mlinker-opt -mlong-calls -mlong-load-store -mno-disable-fpregs -mno-disable-indexing -mno-fast-indirect-calls -mno-gas -mno-jump-in-delay -mno-long-load-store -mno-portable-runtime -mno-soft-float -mno-space-regs -msoft-float -mpa-risc-1-0 -mpa-risc-1-1 -mpa-risc-2-0 -mportable-runtime -mschedule=cpu-type -mspace-regs -msio -mwsio -munix=unix-std -nolibdld -static -threads
IA-64 Options -mbig-endian -mlittle-endian -mgnu-as -mgnu-ld -mno-pic -mvolatile-asm-stop -mregister-names -msdata -mno-sdata -mconstant-gp -mauto-pic -mfused-madd -minline-float-divide-min-latency -minline-float-divide-max-throughput -mno-inline-float-divide -minline-int-divide-min-latency -minline-int-divide-max-throughput -mno-inline-int-divide -minline-sqrt-min-latency -minline-sqrt-max-throughput -mno-inline-sqrt -mdwarf2-asm -mearly-stop-bits -mfixed-range=register-range -mtls-size=tls-size -mtune=cpu-type -milp32 -mlp64 -msched-br-data-spec -msched-ar-data-spec -msched-control-spec -msched-br-in-data-spec -msched-ar-in-data-spec -msched-in-control-spec -msched-spec-ldc -msched-spec-control-ldc -msched-prefer-non-data-spec-insns -msched-prefer-non-control-spec-insns -msched-stop-bits-after-every-cycle -msched-count-spec-in-critical-path -msel-sched-dont-check-control-spec -msched-fp-mem-deps-zero-cost -msched-max-memory-insns-hard-limit -msched-max-memory-insns=max-insns
LM32 Options -mbarrel-shift-enabled -mdivide-enabled -mmultiply-enabled -msign-extend-enabled -muser-enabled
M32R/D Options -m32r2 -m32rx -m32r -mdebug -malign-loops -mno-align-loops -missue-rate=number -mbranch-cost=number -mmodel=code-size-model-type -msdata=sdata-type -mno-flush-func -mflush-func=name -mno-flush-trap -mflush-trap=number -G num
M32C Options -mcpu=cpu -msim -memregs=number
M680x0 Options -march=arch -mcpu=cpu -mtune=tune -m68000 -m68020 -m68020-40 -m68020-60 -m68030 -m68040 -m68060 -mcpu32 -m5200 -m5206e -m528x -m5307 -m5407 -mcfv4e -mbitfield -mno-bitfield -mc68000 -mc68020 -mnobitfield -mrtd -mno-rtd -mdiv -mno-div -mshort -mno-short -mhard-float -m68881 -msoft-float -mpcrel -malign-int -mstrict-align -msep-data -mno-sep-data -mshared-library-id=n -mid-shared-library -mno-id-shared-library -mxgot -mno-xgot -mlong-jump-table-offsets
MCore Options -mhardlit -mno-hardlit -mdiv -mno-div -mrelax-immediates -mno-relax-immediates -mwide-bitfields -mno-wide-bitfields -m4byte-functions -mno-4byte-functions -mcallgraph-data -mno-callgraph-data -mslow-bytes -mno-slow-bytes -mno-lsim -mlittle-endian -mbig-endian -m210 -m340 -mstack-increment
MeP Options -mabsdiff -mall-opts -maverage -mbased=n -mbitops -mc=n -mclip -mconfig=name -mcop -mcop32 -mcop64 -mivc2 -mdc -mdiv -meb -mel -mio-volatile -ml -mleadz -mm -mminmax -mmult -mno-opts -mrepeat -ms -msatur -msdram -msim -msimnovec -mtf -mtiny=n
MicroBlaze Options -msoft-float -mhard-float -msmall-divides -mcpu=cpu -mmemcpy -mxl-soft-mul -mxl-soft-div -mxl-barrel-shift -mxl-pattern-compare -mxl-stack-check -mxl-gp-opt -mno-clearbss -mxl-multiply-high -mxl-float-convert -mxl-float-sqrt -mbig-endian -mlittle-endian -mxl-reorder -mxl-mode-app-model
MIPS Options -EL -EB -march=arch -mtune=arch -mips1 -mips2 -mips3 -mips4 -mips32 -mips32r2 -mips32r3 -mips32r5 -mips32r6 -mips64 -mips64r2 -mips64r3 -mips64r5 -mips64r6 -mips16 -mno-mips16 -mflip-mips16 -minterlink-compressed -mno-interlink-compressed -minterlink-mips16 -mno-interlink-mips16 -mabi=abi -mabicalls -mno-abicalls -mshared -mno-shared -mplt -mno-plt -mxgot -mno-xgot -mgp32 -mgp64 -mfp32 -mfpxx -mfp64 -mhard-float -msoft-float -mno-float -msingle-float -mdouble-float -modd-spreg -mno-odd-spreg -mabs=mode -mnan=encoding -mdsp -mno-dsp -mdspr2 -mno-dspr2 -mmcu -mmno-mcu -meva -mno-eva -mvirt -mno-virt -mxpa -mno-xpa -mmicromips -mno-micromips -mmsa -mno-msa -mfpu=fpu-type -msmartmips -mno-smartmips -mpaired-single -mno-paired-single -mdmx -mno-mdmx -mips3d -mno-mips3d -mmt -mno-mt -mllsc -mno-llsc -mlong64 -mlong32 -msym32 -mno-sym32 -Gnum -mlocal-sdata -mno-local-sdata -mextern-sdata -mno-extern-sdata -mgpopt -mno-gopt -membedded-data -mno-embedded-data -muninit-const-in-rodata -mno-uninit-const-in-rodata -mcode-readable=setting -msplit-addresses -mno-split-addresses -mexplicit-relocs -mno-explicit-relocs -mcheck-zero-division -mno-check-zero-division -mdivide-traps -mdivide-breaks -mload-store-pairs -mno-load-store-pairs -mmemcpy -mno-memcpy -mlong-calls -mno-long-calls -mmad -mno-mad -mimadd -mno-imadd -mfused-madd -mno-fused-madd -nocpp -mfix-24k -mno-fix-24k -mfix-r4000 -mno-fix-r4000 -mfix-r4400 -mno-fix-r4400 -mfix-r10000 -mno-fix-r10000 -mfix-rm7000 -mno-fix-rm7000 -mfix-vr4120 -mno-fix-vr4120 -mfix-vr4130 -mno-fix-vr4130 -mfix-sb1 -mno-fix-sb1 -mflush-func=func -mno-flush-func -mbranch-cost=num -mbranch-likely -mno-branch-likely -mcompact-branches=policy -mfp-exceptions -mno-fp-exceptions -mvr4130-align -mno-vr4130-align -msynci -mno-synci -mlxc1-sxc1 -mno-lxc1-sxc1 -mmadd4 -mno-madd4 -mrelax-pic-calls -mno-relax-pic-calls -mmcount-ra-address -mframe-header-opt -mno-frame-header-opt
MMIX Options -mlibfuncs -mno-libfuncs -mepsilon -mno-epsilon -mabi=gnu -mabi=mmixware -mzero-extend -mknuthdiv -mtoplevel-symbols -melf -mbranch-predict -mno-branch-predict -mbase-addresses -mno-base-addresses -msingle-exit -mno-single-exit
MN10300 Options -mmult-bug -mno-mult-bug -mno-am33 -mam33 -mam33-2 -mam34 -mtune=cpu-type -mreturn-pointer-on-d0 -mno-crt0 -mrelax -mliw -msetlb
Moxie Options -meb -mel -mmul.x -mno-crt0
MSP430 Options -msim -masm-hex -mmcu= -mcpu= -mlarge -msmall -mrelax -mwarn-mcu -mcode-region= -mdata-region= -msilicon-errata= -msilicon-errata-warn= -mhwmult= -minrt
NDS32 Options -mbig-endian -mlittle-endian -mreduced-regs -mfull-regs -mcmov -mno-cmov -mperf-ext -mno-perf-ext -mv3push -mno-v3push -m16bit -mno-16bit -misr-vector-size=num -mcache-block-size=num -march=arch -mcmodel=code-model -mctor-dtor -mrelax
Nios II Options -G num -mgpopt=option -mgpopt -mno-gpopt -mel -meb -mno-bypass-cache -mbypass-cache -mno-cache-volatile -mcache-volatile -mno-fast-sw-div -mfast-sw-div -mhw-mul -mno-hw-mul -mhw-mulx -mno-hw-mulx -mno-hw-div -mhw-div -mcustom-insn=N -mno-custom-insn -mcustom-fpu-cfg=name -mhal -msmallc -msys-crt0=name -msys-lib=name -march=arch -mbmx -mno-bmx -mcdx -mno-cdx
Nvidia PTX Options -m32 -m64 -mmainkernel -moptimize
PDP-11 Options -mfpu -msoft-float -mac0 -mno-ac0 -m40 -m45 -m10 -mbcopy -mbcopy-builtin -mint32 -mno-int16 -mint16 -mno-int32 -mfloat32 -mno-float64 -mfloat64 -mno-float32 -mabshi -mno-abshi -mbranch-expensive -mbranch-cheap -munix-asm -mdec-asm
picoChip Options -mae=ae_type -mvliw-lookahead=N -msymbol-as-address -mno-inefficient-warnings
PowerPC Options See RS/6000 and PowerPC Options.
RISC-V Options -mbranch-cost=N-instruction -mplt -mno-plt -mabi=ABI-string -mfdiv -mno-fdiv -mdiv -mno-div -march=ISA-string -mtune=processor-string -msmall-data-limit=N-bytes -msave-restore -mno-save-restore -mstrict-align -mno-strict-align -mcmodel=medlow -mcmodel=medany -mexplicit-relocs -mno-explicit-relocs
RL78 Options -msim -mmul=none -mmul=g13 -mmul=g14 -mallregs -mcpu=g10 -mcpu=g13 -mcpu=g14 -mg10 -mg13 -mg14 -m64bit-doubles -m32bit-doubles -msave-mduc-in-interrupts
RS/6000 and PowerPC Options -mcpu=cpu-type -mtune=cpu-type -mcmodel=code-model -mpowerpc64 -maltivec -mno-altivec -mpowerpc-gpopt -mno-powerpc-gpopt -mpowerpc-gfxopt -mno-powerpc-gfxopt -mmfcrf -mno-mfcrf -mpopcntb -mno-popcntb -mpopcntd -mno-popcntd -mfprnd -mno-fprnd -mcmpb -mno-cmpb -mmfpgpr -mno-mfpgpr -mhard-dfp -mno-hard-dfp -mfull-toc -mminimal-toc -mno-fp-in-toc -mno-sum-in-toc -m64 -m32 -mxl-compat -mno-xl-compat -mpe -malign-power -malign-natural -msoft-float -mhard-float -mmultiple -mno-multiple -msingle-float -mdouble-float -msimple-fpu -mstring -mno-string -mupdate -mno-update -mavoid-indexed-addresses -mno-avoid-indexed-addresses -mfused-madd -mno-fused-madd -mbit-align -mno-bit-align -mstrict-align -mno-strict-align -mrelocatable -mno-relocatable -mrelocatable-lib -mno-relocatable-lib -mtoc -mno-toc -mlittle -mlittle-endian -mbig -mbig-endian -mdynamic-no-pic -maltivec -mswdiv -msingle-pic-base -mprioritize-restricted-insns=priority -msched-costly-dep=dependence_type -minsert-sched-nops=scheme -mcall-sysv -mcall-netbsd -maix-struct-return -msvr4-struct-return -mabi=abi-type -msecure-plt -mbss-plt -mblock-move-inline-limit=num -misel -mno-isel -misel=yes -misel=no -mspe -mno-spe -mspe=yes -mspe=no -mpaired -mgen-cell-microcode -mwarn-cell-microcode -mvrsave -mno-vrsave -mmulhw -mno-mulhw -mdlmzb -mno-dlmzb -mfloat-gprs=yes -mfloat-gprs=no -mfloat-gprs=single -mfloat-gprs=double -mprototype -mno-prototype -msim -mmvme -mads -myellowknife -memb -msdata -msdata=opt -mreadonly-in-sdata -mvxworks -G num -mrecip -mrecip=opt -mno-recip -mrecip-precision -mno-recip-precision -mveclibabi=type -mfriz -mno-friz -mpointers-to-nested-functions -mno-pointers-to-nested-functions -msave-toc-indirect -mno-save-toc-indirect -mpower8-fusion -mno-mpower8-fusion -mpower8-vector -mno-power8-vector -mcrypto -mno-crypto -mhtm -mno-htm -mdirect-move -mno-direct-move -mquad-memory -mno-quad-memory -mquad-memory-atomic -mno-quad-memory-atomic -mcompat-align-parm -mno-compat-align-parm -mupper-regs-df -mno-upper-regs-df -mupper-regs-sf -mno-upper-regs-sf -mupper-regs-di -mno-upper-regs-di -mupper-regs -mno-upper-regs -mfloat128 -mno-float128 -mfloat128-hardware -mno-float128-hardware -mgnu-attribute -mno-gnu-attribute -mstack-protector-guard=guard -mstack-protector-guard-reg=reg -mstack-protector-guard-offset=offset -mlra -mno-lra
RX Options -m64bit-doubles -m32bit-doubles -fpu -nofpu -mcpu= -mbig-endian-data -mlittle-endian-data -msmall-data -msim -mno-sim -mas100-syntax -mno-as100-syntax -mrelax -mmax-constant-size= -mint-register= -mpid -mallow-string-insns -mno-allow-string-insns -mjsr -mno-warn-multiple-fast-interrupts -msave-acc-in-interrupts
S/390 and zSeries Options -mtune=cpu-type -march=cpu-type -mhard-float -msoft-float -mhard-dfp -mno-hard-dfp -mlong-double-64 -mlong-double-128 -mbackchain -mno-backchain -mpacked-stack -mno-packed-stack -msmall-exec -mno-small-exec -mmvcle -mno-mvcle -m64 -m31 -mdebug -mno-debug -mesa -mzarch -mhtm -mvx -mzvector -mtpf-trace -mno-tpf-trace -mfused-madd -mno-fused-madd -mwarn-framesize -mwarn-dynamicstack -mstack-size -mstack-guard -mhotpatch=halfwords,halfwords
Score Options -meb -mel -mnhwloop -muls -mmac -mscore5 -mscore5u -mscore7 -mscore7d
SH Options -m1 -m2 -m2e -m2a-nofpu -m2a-single-only -m2a-single -m2a -m3 -m3e -m4-nofpu -m4-single-only -m4-single -m4 -m4a-nofpu -m4a-single-only -m4a-single -m4a -m4al -mb -ml -mdalign -mrelax -mbigtable -mfmovd -mrenesas -mno-renesas -mnomacsave -mieee -mno-ieee -mbitops -misize -minline-ic_invalidate -mpadstruct -mprefergot -musermode -multcost=number -mdiv=strategy -mdivsi3_libfunc=name -mfixed-range=register-range -maccumulate-outgoing-args -matomic-model=atomic-model -mbranch-cost=num -mzdcbranch -mno-zdcbranch -mcbranch-force-delay-slot -mfused-madd -mno-fused-madd -mfsca -mno-fsca -mfsrra -mno-fsrra -mpretend-cmove -mtas
Solaris 2 Options -mclear-hwcap -mno-clear-hwcap -mimpure-text -mno-impure-text -pthreads
SPARC Options -mcpu=cpu-type -mtune=cpu-type -mcmodel=code-model -mmemory-model=mem-model -m32 -m64 -mapp-regs -mno-app-regs -mfaster-structs -mno-faster-structs -mflat -mno-flat -mfpu -mno-fpu -mhard-float -msoft-float -mhard-quad-float -msoft-quad-float -mstack-bias -mno-stack-bias -mstd-struct-return -mno-std-struct-return -munaligned-doubles -mno-unaligned-doubles -muser-mode -mno-user-mode -mv8plus -mno-v8plus -mvis -mno-vis -mvis2 -mno-vis2 -mvis3 -mno-vis3 -mvis4 -mno-vis4 -mvis4b -mno-vis4b -mcbcond -mno-cbcond -mfmaf -mno-fmaf -mfsmuld -mno-fsmuld -mpopc -mno-popc -msubxc -mno-subxc -mfix-at697f -mfix-ut699 -mfix-ut700 -mfix-gr712rc -mlra -mno-lra
SPU Options -mwarn-reloc -merror-reloc -msafe-dma -munsafe-dma -mbranch-hints -msmall-mem -mlarge-mem -mstdmain -mfixed-range=register-range -mea32 -mea64 -maddress-space-conversion -mno-address-space-conversion -mcache-size=cache-size -matomic-updates -mno-atomic-updates
System V Options -Qy -Qn -YP,paths -Ym,dir
TILE-Gx Options -mcpu=CPU -m32 -m64 -mbig-endian -mlittle-endian -mcmodel=code-model
TILEPro Options -mcpu=cpu -m32
V850 Options -mlong-calls -mno-long-calls -mep -mno-ep -mprolog-function -mno-prolog-function -mspace -mtda=n -msda=n -mzda=n -mapp-regs -mno-app-regs -mdisable-callt -mno-disable-callt -mv850e2v3 -mv850e2 -mv850e1 -mv850es -mv850e -mv850 -mv850e3v5 -mloop -mrelax -mlong-jumps -msoft-float -mhard-float -mgcc-abi -mrh850-abi -mbig-switch
VAX Options -mg -mgnu -munix
Visium Options -mdebug -msim -mfpu -mno-fpu -mhard-float -msoft-float -mcpu=cpu-type -mtune=cpu-type -msv-mode -muser-mode
VMS Options -mvms-return-codes -mdebug-main=prefix -mmalloc64 -mpointer-size=size
VxWorks Options -mrtp -non-static -Bstatic -Bdynamic -Xbind-lazy -Xbind-now
x86 Options -mtune=cpu-type -march=cpu-type -mtune-ctrl=feature-list -mdump-tune-features -mno-default -mfpmath=unit -masm=dialect -mno-fancy-math-387 -mno-fp-ret-in-387 -m80387 -mhard-float -msoft-float -mno-wide-multiply -mrtd -malign-double -mpreferred-stack-boundary=num -mincoming-stack-boundary=num -mcld -mcx16 -msahf -mmovbe -mcrc32 -mrecip -mrecip=opt -mvzeroupper -mprefer-avx128 -mmmx -msse -msse2 -msse3 -mssse3 -msse4.1 -msse4.2 -msse4 -mavx -mavx2 -mavx512f -mavx512pf -mavx512er -mavx512cd -mavx512vl -mavx512bw -mavx512dq -mavx512ifma -mavx512vbmi -msha -maes -mpclmul -mfsgsbase -mrdrnd -mf16c -mfma -mprefetchwt1 -mclflushopt -mxsavec -mxsaves -msse4a -m3dnow -m3dnowa -mpopcnt -mabm -mbmi -mtbm -mfma4 -mxop -mlzcnt -mbmi2 -mfxsr -mxsave -mxsaveopt -mrtm -mlwp -mmpx -mmwaitx -mclzero -mpku -mthreads -mms-bitfields -mno-align-stringops -minline-all-stringops -minline-stringops-dynamically -mstringop-strategy=alg -mmemcpy-strategy=strategy -mmemset-strategy=strategy -mpush-args -maccumulate-outgoing-args -m128bit-long-double -m96bit-long-double -mlong-double-64 -mlong-double-80 -mlong-double-128 -mregparm=num -msseregparm -mveclibabi=type -mvect8-ret-in-mem -mpc32 -mpc64 -mpc80 -mstackrealign -momit-leaf-frame-pointer -mno-red-zone -mno-tls-direct-seg-refs -mcmodel=code-model -mabi=name -maddress-mode=mode -m32 -m64 -mx32 -m16 -miamcu -mlarge-data-threshold=num -msse2avx -mfentry -mrecord-mcount -mnop-mcount -m8bit-idiv -mavx256-split-unaligned-load -mavx256-split-unaligned-store -malign-data=type -mstack-protector-guard=guard -mmitigate-rop -mgeneral-regs-only -mindirect-branch=choice -mfunction-return=choice -mindirect-branch-register
x86 Windows Options -mconsole -mcygwin -mno-cygwin -mdll -mnop-fun-dllimport -mthread -municode -mwin32 -mwindows -fno-set-stack-executable
Xstormy16 Options -msim
Xtensa Options -mconst16 -mno-const16 -mfused-madd -mno-fused-madd -mforce-no-pic -mserialize-volatile -mno-serialize-volatile -mtext-section-literals -mno-text-section-literals -mauto-litpools -mno-auto-litpools -mtarget-align -mno-target-align -mlongcalls -mno-longcalls
zSeries Options See S/390 and zSeries Options.
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:
You can specify the input language explicitly with the -x option:
c c-header 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 go brig
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.
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.
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.
Input files that don't require preprocessing are ignored.
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.
These are the supported qualifiers:
Thus for example to display all the undocumented target-specific switches supported by the compiler, use:
--help=target,undocumented
The sense of a qualifier can be inverted by prefixing it with the ^ character, so for example to display all binary warning options (i.e., ones that are either on or off and that do not take an argument) that have a description, use:
--help=warnings,^joined,^undocumented
The argument to --help= should not consist solely of inverted qualifiers.
Combining several classes is possible, although this usually restricts the output so much that there is nothing to display. One case where it does work, however, is when one of the classes is target. For example, to display all the target-specific optimization options, use:
--help=target,optimizers
The --help= option can be repeated on the command line. Each successive use displays its requested class of options, skipping those that have already been displayed.
If 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
gcc -c t.c -wrapper gdb,--args
This invokes all subprograms of gcc under gdb --args, thus the invocation of cc1 is gdb --args cc1 ....
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.
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 automatically specifies linking against the C++ library. It treats .c, .h and .i files as C++ source files instead of C source files unless -x is used. 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.
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:
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, -Wpedantic 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 are normally 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.
The compiler can accept several base standards, such as c90 or c++98, and GNU dialects of those standards, such as gnu90 or gnu++98. When a base standard is specified, the compiler accepts all programs following that standard plus those using GNU extensions that do not contradict it. For example, -std=c90 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, when a GNU dialect of a standard is specified, all features supported by the compiler are enabled, even when those features change the meaning of the base standard. As a result, some strict-conforming programs may be rejected. The particular standard is used by -Wpedantic to identify which features are GNU extensions given that version of the standard. For example -std=gnu90 -Wpedantic warns about C++ style // comments, while -std=gnu99 -Wpedantic does not.
A value for this option must be provided; possible values are
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 is not supported in -std=c90 or -std=gnu90 mode.
The preprocessor macros "__GNUC_GNU_INLINE__" and "__GNUC_STDC_INLINE__" may be used to check which semantics are in effect for "inline" functions.
-fpermitted-flt-eval-methods specifies whether the compiler should allow only the values of "FLT_EVAL_METHOD" specified in C99/C11, or the extended set of values specified in ISO/IEC TS 18661-3.
style is either "c11" or "ts-18661-3" as appropriate.
The default when in a standards compliant mode (-std=c11 or similar) is -fpermitted-flt-eval-methods=c11. The default when in a GNU dialect (-std=gnu11 or similar) is -fpermitted-flt-eval-methods=ts-18661-3.
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.
Although it is possible to define such a function, this is not very useful as it is not possible to read the arguments. This is only supported for C as this construct is allowed by C++.
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.
GCC normally generates special code to handle certain built-in functions more efficiently; for instance, calls to "alloca" may become single instructions which adjust the stack directly, and calls to "memcpy" may become inline copy loops. 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))
For more information on GCC's support for transactional memory,
Note that the transactional memory feature is not supported with non-call exceptions (-fnon-call-exceptions).
In C++ code, this allows member names in structures to be similar to previous types declarations.
typedef int UOW; struct ABC { UOW UOW; };
Some cases of unnamed fields in structures and unions are only accepted with this option.
Note that this option is off for all targets but x86 targets using ms-abi.
This enables -fms-extensions, permits passing pointers to structures with anonymous fields to functions that expect pointers to elements of the type of the field, and permits referring to anonymous fields declared using a typedef. This is only supported for C, not C++.
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.
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.
Warning: the -fsso-struct switch causes GCC to generate code that is not binary compatible with code generated without it if the specified endianness is not the native endianness of the target.
This section describes the command-line options that are only meaningful for C++ programs. 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 -fstrict-enums -O -c firstClass.C
In this example, only -fstrict-enums is an option meant only for C++ programs; you can use the other options with any language supported by GCC.
Some options for compiling C programs, such as -std, are also relevant for C++ programs.
Here is a list of options that are only for compiling C++ programs:
Version 0 refers to the version conforming most closely to the C++ ABI specification. Therefore, the ABI obtained using version 0 will change in different versions of G++ as ABI bugs are fixed.
Version 1 is the version of the C++ ABI that first appeared in G++ 3.2.
Version 2 is the version of the C++ ABI that first appeared in G++ 3.4, and was the default through G++ 4.9.
Version 3 corrects an error in mangling a constant address as a template argument.
Version 4, which first appeared in G++ 4.5, implements a standard mangling for vector types.
Version 5, which first appeared in G++ 4.6, corrects the mangling of attribute const/volatile on function pointer types, decltype of a plain decl, and use of a function parameter in the declaration of another parameter.
Version 6, which first appeared in G++ 4.7, corrects the promotion behavior of C++11 scoped enums and the mangling of template argument packs, const/static_cast, prefix ++ and --, and a class scope function used as a template argument.
Version 7, which first appeared in G++ 4.8, that treats nullptr_t as a builtin type and corrects the mangling of lambdas in default argument scope.
Version 8, which first appeared in G++ 4.9, corrects the substitution behavior of function types with function-cv-qualifiers.
Version 9, which first appeared in G++ 5.2, corrects the alignment of "nullptr_t".
Version 10, which first appeared in G++ 6.1, adds mangling of attributes that affect type identity, such as ia32 calling convention attributes (e.g. stdcall).
Version 11, which first appeared in G++ 7, corrects the mangling of sizeof... expressions and operator names. For multiple entities with the same name within a function, that are declared in different scopes, the mangling now changes starting with the twelfth occurrence. It also implies -fnew-inheriting-ctors.
See also -Wabi.
With -fabi-version=0 (the default), this defaults to 8 (GCC 5 compatibility). If another ABI version is explicitly selected, this defaults to 0. For compatibility with GCC versions 3.2 through 4.9, use -fabi-compat-version=2.
If this option is not provided but -Wabi=n is, that version is used for compatibility aliases. If this option is provided along with -Wabi (without the version), the version from this option is used for the warning.
template <class T> concept bool Addable = requires (T t) { t + t; }; template <Addable T> T add (T a, T b) { return a + b; }
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 deduction was implemented as a possible extension to the originally proposed semantics for the C++11 standard, but was not part of the final standard, so it is disabled by default. This option is deprecated, and may be removed in a future version of G++.
This option is for compatibility, and may be removed in a future release of G++.
In C++17, the compiler is required to omit these temporaries, but this option still affects trivial member functions.
On targets that support symbol aliases, the default is -fextern-tls-init. On targets that do not support symbol aliases, the default is -fno-extern-tls-init.
If neither flag is given, the default is to follow the standard, but to allow and give a warning for old-style code that would otherwise be invalid, or have different behavior.
void operator delete (void *, std::size_t) noexcept; void operator delete[] (void *, std::size_t) noexcept;
as introduced in C++14. This is useful for user-defined replacement deallocation functions that, for example, use the size of the object to make deallocation faster. Enabled by default under -std=c++14 and above. The flag -Wsized-deallocation warns about places that might want to add a definition.
The effect of this is that GCC may, effectively, mark inline methods with "__attribute__ ((visibility ("hidden")))" so that they do not appear in the export table of a DSO and do not require a PLT indirection when used within the DSO. Enabling this option can have a dramatic effect on load and link times of a DSO as it massively reduces the size of the dynamic export table when the library makes heavy use of templates.
The behavior of this switch is not quite the same as marking the methods as hidden directly, because it does not affect static variables local to the function or cause the compiler to deduce that the function is defined in only one shared object.
You may mark a method as having a visibility explicitly to negate the effect of the switch for that method. For example, if you do want to compare pointers to a particular inline method, you might mark it as having default visibility. Marking the enclosing class with explicit visibility has no effect.
Explicitly instantiated inline methods are unaffected by this option as their linkage might otherwise cross a shared library boundary.
The flag makes these changes to GCC's linkage model:
In new code it is better to use -fvisibility=hidden and export those classes that are intended to be externally visible. Unfortunately it is possible for code to rely, perhaps accidentally, on the Visual Studio behavior.
Among the consequences of these changes are that static data members of the same type with the same name but defined in different shared objects are different, so changing one does not change the other; and that pointers to function members defined in different shared objects may not compare equal. When this flag is given, it is a violation of the ODR to define types with the same name differently.
In addition, these optimization, warning, and code generation options have meanings only for C++ programs:
-Wabi can also be used with an explicit version number to warn about compatibility with a particular -fabi-version level, e.g. -Wabi=2 to warn about changes relative to -fabi-version=2.
If an explicit version number is provided and -fabi-compat-version is not specified, the version number from this option is used for compatibility aliases. If no explicit version number is provided with this option, but -fabi-compat-version is specified, that version number is used for ABI warnings.
Although an effort has been made to warn about all such cases, there are probably some cases that are not warned about, even though G++ is generating incompatible code. There may also be cases where warnings are emitted even though the code that is generated is compatible.
You should rewrite your code to avoid these warnings if you are concerned about the fact that code generated by G++ may not be binary compatible with code generated by other compilers.
Known incompatibilities in -fabi-version=2 (which was the default from GCC 3.4 to 4.9) include:
extern int N; template <int &> struct S {}; void n (S<N>) {2}
This was fixed in -fabi-version=3.
The mangling was changed in -fabi-version=4.
These mangling issues were fixed in -fabi-version=5.
Also, the ABI changed the mangling of template argument packs, "const_cast", "static_cast", prefix increment/decrement, and a class scope function used as a template argument.
These issues were corrected in -fabi-version=6.
These issues were corrected in -fabi-version=7.
This was fixed in -fabi-version=8, the default for GCC 5.1.
This was fixed in -fabi-version=9, the default for GCC 5.2.
This was fixed in -fabi-version=10, the default for GCC 6.1.
It also warns about psABI-related changes. The known psABI changes at this point include:
union U { long double ld; int i; };
"union U" is always passed in memory.
#define __STDC_FORMAT_MACROS #include <inttypes.h> #include <stdio.h> int main() { int64_t i64 = 123; printf("My int64: %" PRId64"\n", i64); }
In this case, "PRId64" is treated as a separate preprocessing token.
Additionally, warn when a user-defined literal operator is declared with a literal suffix identifier that doesn't begin with an underscore. Literal suffix identifiers that don't begin with an underscore are reserved for future standardization.
This warning is enabled by default.
With -Wnarrowing in C++98, warn when a narrowing conversion prohibited by C++11 occurs within { }, e.g.
int i = { 2.2 }; // error: narrowing from double to int
This flag is included in -Wall and -Wc++11-compat.
template <class T> void f(T t) { t(); }; void g() noexcept; void h() { f(g); } // in C++14 calls f<void(*)()>, in C++1z calls f<void(*)()noexcept>
struct A { int i; int j; A(): j (0), i (1) { } };
The compiler rearranges the member initializers for "i" and "j" to match the declaration order of the members, emitting a warning to that effect. This warning is enabled by -Wall.
The following -W... options are not affected by -Wall.
This option also enables -Wnon-virtual-dtor, which is also one of the effective C++ recommendations. However, the check is extended to warn about the lack of virtual destructor in accessible non-polymorphic bases classes too.
When selecting this option, be aware that the standard library headers do not obey all of these guidelines; use grep -v to filter out those warnings.
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();
fails to compile.
(NOTE: This manual does not describe the Objective-C and Objective-C++ languages themselves.
This section describes the command-line options that are only meaningful for Objective-C and Objective-C++ programs. 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:
The "- (id) .cxx_construct" and "- (void) .cxx_destruct" methods thusly generated only operate on instance variables declared in the current Objective-C class, and not those inherited from superclasses. It is the responsibility of the Objective-C runtime to invoke all such methods in an object's inheritance hierarchy. The "- (id) .cxx_construct" methods are invoked by the runtime immediately after a new object instance is allocated; the "- (void) .cxx_destruct" methods are invoked immediately before the runtime deallocates an object instance.
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.
Traditionally, diagnostic messages have been formatted irrespective of the output device's aspect (e.g. its width, ...). You can use the options described below to control the formatting algorithm for diagnostic messages, e.g. how many characters per line, how often source location information should be reported. Note that some language front ends may not honor these options.
The colors are defined by the environment variable GCC_COLORS. Its value is a colon-separated list of capabilities and Select Graphic Rendition (SGR) substrings. SGR commands are interpreted by the terminal or terminal emulator. (See the section in the documentation of your text terminal for permitted values and their meanings as character attributes.) These substring values are integers in decimal representation and can be concatenated with semicolons. Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors.
The default GCC_COLORS is
error=01;31:warning=01;35:note=01;36:range1=32:range2=34:locus=01:\ quote=01:fixit-insert=32:fixit-delete=31:\ diff-filename=01:diff-hunk=32:diff-delete=31:diff-insert=32
where 01;31 is bold red, 01;35 is bold magenta, 01;36 is bold cyan, 32 is green, 34 is blue, 01 is bold, and 31 is red. Setting GCC_COLORS to the empty string disables colors. Supported capabilities are as follows.
fix-it:"test.c":{45:3-45:21}:"gtk_widget_show_all"
The location is expressed as a half-open range, expressed as a count of bytes, starting at byte 1 for the initial column. In the above example, bytes 3 through 20 of line 45 of "test.c" are to be replaced with the given string:
00000000011111111112222222222 12345678901234567890123456789 gtk_widget_showall (dlg); ^^^^^^^^^^^^^^^^^^ gtk_widget_show_all
The filename and replacement string escape backslash as "\\", tab as "\t", newline as "\n", double quotes as "\"", non-printable characters as octal (e.g. vertical tab as "\013").
An empty replacement string indicates that the given range is to be removed. An empty range (e.g. "45:3-45:3") indicates that the string is to be inserted at the given position.
--- test.c +++ test.c @ -42,5 +42,5 @ void show_cb(GtkDialog *dlg) { - gtk_widget_showall(dlg); + gtk_widget_show_all(dlg); }
The diff may or may not be colorized, following the same rules as for diagnostics (see -fdiagnostics-color).
Warnings are diagnostic messages that report constructions that are not inherently erroneous but that 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.
The warning message for each controllable warning includes the option that controls the warning. That option can then be used with -Werror= and -Wno-error= as described above. (Printing of the option in the warning message can be disabled using the -fno-diagnostics-show-option flag.)
Note that specifying -Werror=foo automatically implies -Wfoo. However, -Wno-error=foo does not imply anything.
You can request many specific warnings with options beginning with -W, for example -Wimplicit to request warnings on implicit declarations. Each of these specific warning options also has a negative form beginning -Wno- to turn off warnings; for example, -Wno-implicit. This manual lists only one of the two forms, whichever is not the default. For further language-specific options also refer to C++ Dialect Options and Objective-C and Objective-C++ Dialect Options.
Some options, such as -Wall and -Wextra, turn on other options, such as -Wunused, which may turn on further options, such as -Wunused-value. The combined effect of positive and negative forms is that more specific options have priority over less specific ones, independently of their position in the command-line. For options of the same specificity, the last one takes effect. Options enabled or disabled via pragmas take effect as if they appeared at the end of the command-line.
When an unrecognized warning option is requested (e.g., -Wunknown-warning), GCC emits a diagnostic stating that the option is not recognized. However, if the -Wno- form is used, the behavior is slightly different: no diagnostic is produced for -Wno-unknown-warning unless other diagnostics are being produced. This allows the use of new -Wno- options with old compilers, but if something goes wrong, the compiler warns that an unrecognized option is present.
Valid ISO C and ISO C++ programs should compile properly with or without this option (though a rare few require -ansi or a -std option specifying the 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.
-Wpedantic 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 -Wpedantic 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 -Wpedantic. 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 gnu90 or gnu99, there is a corresponding base standard, the version of ISO C on which the GNU extended dialect is based. Warnings from -Wpedantic are given where they are required by the base standard. (It does not make sense for such warnings to be given only for features not in the specified GNU C dialect, since by definition the GNU dialects of C include all features the compiler supports with the given option, and there would be nothing to warn about.)
-Wall turns on the following warning flags:
-Waddress -Warray-bounds=1 (only with -O2) -Wbool-compare -Wbool-operation -Wc++11-compat -Wc++14-compat -Wchar-subscripts -Wcomment -Wduplicate-decl-specifier (C and Objective-C only) -Wenum-compare (in C/ObjC; this is on by default in C++) -Wformat -Wint-in-bool-context -Wimplicit (C and Objective-C only) -Wimplicit-int (C and Objective-C only) -Wimplicit-function-declaration (C and Objective-C only) -Winit-self (only for C++) -Wlogical-not-parentheses -Wmain (only for C/ObjC and unless -ffreestanding) -Wmaybe-uninitialized -Wmemset-elt-size -Wmemset-transposed-args -Wmisleading-indentation (only for C/C++) -Wmissing-braces (only for C/ObjC) -Wnarrowing (only for C++) -Wnonnull -Wnonnull-compare -Wopenmp-simd -Wparentheses -Wpointer-sign -Wreorder -Wreturn-type -Wsequence-point -Wsign-compare (only in C++) -Wsizeof-pointer-memaccess -Wstrict-aliasing -Wstrict-overflow=1 -Wswitch -Wtautological-compare -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.
-Wclobbered -Wempty-body -Wignored-qualifiers -Wimplicit-fallthrough=3 -Wmissing-field-initializers -Wmissing-parameter-type (C only) -Wold-style-declaration (C only) -Woverride-init -Wsign-compare (C only) -Wtype-limits -Wuninitialized -Wshift-negative-value (in C++03 and in C99 and newer) -Wunused-parameter (only with -Wunused or -Wall) -Wunused-but-set-parameter (only with -Wunused or -Wall)
The option -Wextra also prints warning messages for the following cases:
Suppress warning messages emitted by "#warning" directives.
It is easy to accidentally do computations with "double" because floating-point literals are implicitly of type "double". For example, in:
float area(float radius) { return 3.14159 * radius * radius; }
the compiler performs the entire computation with "double" because the floating-point literal is a "double".
The formats are checked against the format features supported by GNU libc version 2.2. These include all ISO C90 and C99 features, as well as features from the Single Unix Specification and some BSD and GNU extensions. Other library implementations may not support all these features; GCC does not support warning about features that go beyond a particular library's limitations. However, if -Wpedantic is used with -Wformat, warnings are given about format features not in the selected standard version (but not for "strfmon" formats, since those are not in any version of the C standard).
Where the unused arguments lie between used arguments that are specified with $ operand number specifications, normally warnings are still given, since the implementation could not know what type to pass to "va_arg" to skip the unused arguments. However, in the case of "scanf" formats, this option suppresses the warning if the unused arguments are all pointers, since the Single Unix Specification says that such unused arguments are allowed.
void f (int a, int b) { char buf [12]; sprintf (buf, "a = %i, b = %i\n", a, b); }
At level 2, the call in the example above is again diagnosed, but this time because with a equal to a 32-bit "INT_MIN" the first %i directive will write some of its digits beyond the end of the destination buffer. To make the call safe regardless of the values of the two variables, the size of the destination buffer must be increased to at least 34 bytes. GCC includes the minimum size of the buffer in an informational note following the warning.
An alternative to increasing the size of the destination buffer is to constrain the range of formatted values. The maximum length of string arguments can be bounded by specifying the precision in the format directive. When numeric arguments of format directives can be assumed to be bounded by less than the precision of their type, choosing an appropriate length modifier to the format specifier will reduce the required buffer size. For example, if a and b in the example above can be assumed to be within the precision of the "short int" type then using either the %hi format directive or casting the argument to "short" reduces the maximum required size of the buffer to 24 bytes.
void f (int a, int b) { char buf [23]; sprintf (buf, "a = %hi, b = %i\n", a, (short)b); }
-Wnonnull is included in -Wall and -Wformat. It can be disabled with the -Wno-nonnull option.
-Wnonnull-compare is included in -Wall. It can be disabled with the -Wno-nonnull-compare option.
For example, GCC warns about "i" being uninitialized in the following snippet only when -Winit-self has been specified:
int f() { int i = i; return i; }
This warning is enabled by -Wall in C++.
switch (cond) { case 1: a = 1; break; case 2: a = 2; case 3: a = 3; break; }
This warning does not warn when the last statement of a case cannot fall through, e.g. when there is a return statement or a call to function declared with the noreturn attribute. -Wimplicit-fallthrough= also takes into account control flow statements, such as ifs, and only warns when appropriate. E.g.
switch (cond) { case 1: if (i > 3) { bar (5); break; } else if (i < 1) { bar (0); } else return; default: ... }
Since there are occasions where a switch case fall through is desirable, GCC provides an attribute, "__attribute__ ((fallthrough))", that is to be used along with a null statement to suppress this warning that would normally occur:
switch (cond) { case 1: bar (0); __attribute__ ((fallthrough)); default: ... }
C++17 provides a standard way to suppress the -Wimplicit-fallthrough warning using "[[fallthrough]];" instead of the GNU attribute. In C++11 or C++14 users can use "[[gnu::fallthrough]];", which is a GNU extension. Instead of the these attributes, it is also possible to add a fallthrough comment to silence the warning. The whole body of the C or C++ style comment should match the given regular expressions listed below. The option argument n specifies what kind of comments are accepted:
The comment needs to be followed after optional whitespace and other comments by "case" or "default" keywords or by a user label that precedes some "case" or "default" label.
switch (cond) { case 1: bar (0); /* FALLTHRU */ default: ... }
The -Wimplicit-fallthrough=3 warning is enabled by -Wextra.
This warning is also enabled by -Wextra.
In the following example, the call to "bar" is misleadingly indented as if it were guarded by the "if" conditional.
if (some_condition ()) foo (); bar (); /* Gotcha: this is not guarded by the "if". */
In the case of mixed tabs and spaces, the warning uses the -ftabstop= option to determine if the statements line up (defaulting to 8).
The warning is not issued for code involving multiline preprocessor logic such as the following example.
if (flagA) foo (0); #if SOME_CONDITION_THAT_DOES_NOT_HOLD if (flagB) #endif foo (1);
The warning is not issued after a "#line" directive, since this typically indicates autogenerated code, and no assumptions can be made about the layout of the file that the directive references.
This warning is enabled by -Wall in C and C++.
int a[2][2] = { 0, 1, 2, 3 }; int b[2][2] = { { 0, 1 }, { 2, 3 } };
This warning is enabled by -Wall.
Also warn if a comparison like "x<=y<=z" appears; this is equivalent to "(x<=y ? 1 : 0) <= z", which is a different interpretation from that of ordinary mathematical notation.
Also warn for dangerous uses of the GNU extension to "?:" with omitted middle operand. When the condition in the "?": operator is a boolean expression, the omitted value is always 1. Often programmers expect it to be a value computed inside the conditional expression instead.
This warning is enabled by -Wall.
The C and C++ standards define the order in which expressions in a C/C++ program are evaluated in terms of sequence points, which represent a partial ordering between the execution of parts of the program: those executed before the sequence point, and those executed after it. These occur after the evaluation of a full expression (one which is not part of a larger expression), after the evaluation of the first operand of a "&&", "||", "? :" or "," (comma) operator, before a function is called (but after the evaluation of its arguments and the expression denoting the called function), and in certain other places. Other than as expressed by the sequence point rules, the order of evaluation of subexpressions of an expression is not specified. All these rules describe only a partial order rather than a total order, since, for example, if two functions are called within one expression with no sequence point between them, the order in which the functions are called is not specified. However, the standards committee have ruled that function calls do not overlap.
It is not specified when between sequence points modifications to the values of objects take effect. Programs whose behavior depends on this have undefined behavior; the C and C++ standards specify that "Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.". If a program breaks these rules, the results on any particular implementation are entirely unpredictable.
Examples of code with undefined behavior are "a = a++;", "a[n] = b[n++]" and "a[i++] = i;". Some more complicated cases are not diagnosed by this option, and it may give an occasional false positive result, but in general it has been found fairly effective at detecting this sort of problem in programs.
The C++17 standard will define the order of evaluation of operands in more cases: in particular it requires that the right-hand side of an assignment be evaluated before the left-hand side, so the above examples are no longer undefined. But this warning will still warn about them, to help people avoid writing code that is undefined in C and earlier revisions of C++.
The standard is worded confusingly, therefore there is some debate over the precise meaning of the sequence point rules in subtle cases. Links to discussions of the problem, including proposed formal definitions, may be found on the GCC readings page, at <http://gcc.gnu.org/readings.html>.
This warning is enabled by -Wall for C and C++.
For C only, warn about a "return" statement with an expression in a function whose return type is "void", unless the expression type is also "void". As a GNU extension, the latter case is accepted without a warning unless -Wpedantic is used.
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.
switch ((int) (a == 4)) { ... }
This warning is enabled by default for C and C++ programs.
switch (cond) { i = 15; ... case 5: ... }
-Wswitch-unreachable does not warn if the statement between the controlling expression and the first case label is just a declaration:
switch (cond) { int i; ... case 5: i = 5; ... }
This warning is enabled by default for C and C++ programs.
To suppress this warning use the "unused" attribute.
This warning is also enabled by -Wunused together with -Wextra.
To suppress this warning use the "unused" attribute.
This warning is also enabled by -Wunused, which is enabled by -Wall.
To suppress this warning use the "unused" attribute.
To suppress this warning use the "unused" attribute.
To suppress this warning use the "unused" attribute.
To suppress this warning use the "unused" attribute.
This warning is enabled by -Wall.
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.
If you want to warn about code that uses the uninitialized value of the variable in its own initializer, use the -Winit-self option.
These warnings occur for individual uninitialized or clobbered elements of structure, union or array variables as well as for variables that 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 depends 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.
void store (int *i) { __atomic_store_n (i, 0, memory_order_consume); }
-Winvalid-memory-model is enabled by default.
{ int x; switch (y) { case 1: x = 1; break; case 2: x = 4; break; case 3: x = 5; } foo (x); }
If the value of "y" is always 1, 2 or 3, then "x" is always initialized, but GCC doesn't know this. To suppress the warning, you need to provide a default case with assert(0) or similar code.
This option also warns when a non-volatile automatic variable might be changed by a call to "longjmp". 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 that 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.
Level 1: Most aggressive, quick, least accurate. Possibly useful when higher levels do not warn but -fstrict-aliasing still breaks the code, as it has very few false negatives. However, it has many false positives. Warns for all pointer conversions between possibly incompatible types, even if never dereferenced. Runs in the front end only.
Level 2: Aggressive, quick, not too precise. May still have many false positives (not as many as level 1 though), and few false negatives (but possibly more than level 1). Unlike level 1, it only warns when an address is taken. Warns about incomplete types. Runs in the front end only.
Level 3 (default for -Wstrict-aliasing): Should have very few false positives and few false negatives. Slightly slower than levels 1 or 2 when optimization is enabled. Takes care of the common pun+dereference pattern in the front end: "*(int*)&some_float". If optimization is enabled, it also runs in the back end, where it deals with multiple statement cases using flow-sensitive points-to information. Only warns when the converted pointer is dereferenced. Does not warn about incomplete types.
An optimization that assumes that signed overflow does not occur is perfectly safe if the values of the variables involved are such that overflow never does, in fact, occur. Therefore this warning can easily give a false positive: a warning about code that is not actually a problem. To help focus on important issues, several warning levels are defined. No warnings are issued for the use of undefined signed overflow when estimating how many iterations a loop requires, in particular when determining whether a loop will be executed at all.
enum Color { blue, purple, yellow }; const char* f (enum Color clr) { static char buf [4]; const char *str; switch (clr) { case blue: str = "blue"; break; case purple: str = "purple"; break; case yellow: str = "yellow"; break; } return strcpy (buf, str); // warning here }
Option -Wstringop-overflow=2 is enabled by default.
GCC also warns about function definitions that might be candidates for "format" attributes. Again, these are only possible candidates. GCC guesses that "format" attributes might be appropriate for any function that calls a function like "vprintf" or "vscanf", but this might not always be the case, and some functions for which "format" attributes are appropriate may not be detected.
For example, a bounded case of "alloca" could be:
void func (size_t n) { void *p; if (n <= 1000) p = alloca (n); else p = malloc (n); f (p); }
In the above example, passing "-Walloca-larger-than=1000" would not issue a warning because the call to "alloca" is known to be at most 1000 bytes. However, if "-Walloca-larger-than=500" were passed, the compiler would emit a warning.
Unbounded uses, on the other hand, are uses of "alloca" with no controlling predicate constraining its integer argument. For example:
void func () { void *p = alloca (n); f (p); }
If "-Walloca-larger-than=500" were passed, the above would trigger a warning, but this time because of the lack of bounds checking.
Note, that even seemingly correct code involving signed integers could cause a warning:
void func (signed int n) { if (n < 500) { p = alloca (n); f (p); } }
In the above example, n could be negative, causing a larger than expected argument to be implicitly cast into the "alloca" call.
This option also warns when "alloca" is used in a loop.
This warning is not enabled by -Wall, and is only active when -ftree-vrp is active (default for -O2 and above).
See also -Wvla-larger-than=n.
int n = 5; ... if ((n > 1) == 2) { ... }
This warning is enabled by -Wall.
This warning is enabled by -Wall.
if (p != NULL) return 0; else return 0;
It doesn't warn when both branches contain just a null statement. This warning also warn for conditional operators:
int i = x ? *p : *p;
if (p->q != NULL) { ... } else if (p->q != NULL) { ... }
int i = 1; ... if (i > i) { ... }
This warning is enabled by -Wall.
The idea behind this is that sometimes it is convenient (for the programmer) to consider floating-point values as approximations to infinitely precise real numbers. If you are doing this, then you need to compute (by analyzing the code, or in some other way) the maximum or likely maximum error that the computation introduces, and allow for it when performing comparisons (and when producing output, but that's a different problem). In particular, instead of testing for equality, you should check to see whether the two values have ranges that overlap; and this is done with the relational operators, so equality comparisons are probably mistaken.
for (SomeIterator i = SomeObj.begin(); i != SomeObj.end(); ++i) { for (int i = 0; i < N; ++i) { ... } ... }
Since the two variable "i" in the example above have incompatible types, enabling only -Wshadow=compatible-local will not emit a warning. Because their types are incompatible, if a programmer accidentally uses one in place of the other, type checking will catch that and emit an error or warning. So not warning (about shadowing) in this case will not lead to undetected bugs. Use of this flag instead of -Wshadow=local can possibly reduce the number of warnings triggered by intentional shadowing.
This warning is enabled by -Wshadow=local.
The message is in keeping with the output of -fstack-usage.
warning: stack usage is 1120 bytes
warning: stack usage might be 1648 bytes
warning: stack usage might be unbounded
Normally this only warns about global allocation functions, but -Waligned-new=all also warns about class member allocation functions.
char buf [64]; new (buf) int[64];
This warning is enabled by default.
struct S { int n, a[1]; }; S *s = (S *)malloc (sizeof *s + 31 * sizeof s->a[0]); new (s->a)int [32]();
struct S { int n, a[]; }; S *s = (S *)malloc (sizeof *s + 32 * sizeof s->a[0]); new (s->a)int [32]();
const char *p = foo (); if (p == '\0') return 42;
Note that the code above is invalid in C++11.
This warning is enabled by default.
This option is implied by -Wall. If -Wall is not given, this option is still enabled unless trigraphs are enabled. To get trigraph conversion without warnings, but get the other -Wall warnings, use -trigraphs -Wall -Wno-trigraphs.
Built-in macros, macros defined on the command line, and macros defined in include files are not warned about.
Note: If a macro is actually used, but only used in skipped conditional blocks, then the preprocessor reports it as unused. To avoid the warning in such a case, you might improve the scope of the macro's definition by, for example, moving it into the first skipped block. Alternatively, you could provide a dummy use with something like:
#if defined the_macro_causing_the_warning #endif
#if FOO ... #else FOO ... #endif FOO
The second and third "FOO" should be in comments. This warning is on by default.
Also warn when making a cast that introduces a type qualifier in an unsafe way. For example, casting "char **" to "const char **" is unsafe, as in this example:
/* p is char ** value. */ const char **q = (const char **) p; /* Assignment of readonly string to const char * is OK. */ *q = "string"; /* Now char** pointer points to read-only memory. */ **p = 'b';
When compiling C++, warn about the deprecated conversion from string literals to "char *". This warning is enabled by default for C++ programs.
For C++, also warn for confusing overload resolution for user-defined conversions; and conversions that never use a type conversion operator: conversions to "void", the same type, a base class or a reference to them. Warnings about conversions between signed and unsigned integers are disabled by default in C++ unless -Wsign-conversion is explicitly enabled.
{ if (a) if (b) foo (); else bar (); }
In C/C++, every "else" branch belongs to the innermost possible "if" statement, which in this example is "if (b)". This is often not what the programmer expected, as illustrated in the above example by indentation the programmer chose. When there is the potential for this confusion, GCC issues a warning when this flag is specified. To eliminate the warning, add explicit braces around the innermost "if" statement so there is no way the "else" can belong to the enclosing "if". The resulting code looks like this:
{ if (a) { if (b) foo (); else bar (); } }
This warning is enabled by -Wparentheses.
-Wjump-misses-init is included in -Wc++-compat. It can be disabled with the -Wno-jump-misses-init option.
void operator delete (void *) noexcept; void operator delete[] (void *) noexcept;
without a definition of the corresponding sized deallocation function
void operator delete (void *, std::size_t) noexcept; void operator delete[] (void *, std::size_t) noexcept;
or vice versa. Enabled by -Wextra along with -fsized-deallocation.
extern int a; if (a < 0 && a < 0) { ... }
int a; ... if (!a > 1) { ... }
It is possible to suppress the warning by wrapping the LHS into parentheses:
if ((!a) > 1) { ... }
This warning is enabled by -Wall.
void foo(bar) { }
This warning is also enabled by -Wextra.
struct s { int f, g, h; }; struct s x = { 3, 4 };
This option does not warn about designated initializers, so the following modification does not trigger a warning:
struct s { int f, g, h; }; struct s x = { .f = 3, .g = 4 };
In C++ this option does not warn either about the empty { } initializer, for example:
struct s { int f, g, h; }; s x = { };
This warning is included in -Wextra. To get other -Wextra warnings without this one, use -Wextra -Wno-missing-field-initializers.
There are four levels of warning supported by GCC. The default is -Wnormalized=nfc, which warns about any identifier that is not in the ISO 10646 "C" normalized form, NFC. NFC is the recommended form for most uses. It is equivalent to -Wnormalized.
Unfortunately, there are some characters allowed in identifiers by ISO C and ISO C++ that, when turned into NFC, are not allowed in identifiers. That is, there's no way to use these symbols in portable ISO C or C++ and have all your identifiers in NFC. -Wnormalized=id suppresses the warning for these characters. It is hoped that future versions of the standards involved will correct this, which is why this option is not the default.
You can switch the warning off for all characters by writing -Wnormalized=none or -Wno-normalized. You should only do this if you are using some other normalization scheme (like "D"), because otherwise you can easily create bugs that are literally impossible to see.
Some characters in ISO 10646 have distinct meanings but look identical in some fonts or display methodologies, especially once formatting has been applied. For instance "\u207F", "SUPERSCRIPT LATIN SMALL LETTER N", displays just like a regular "n" that has been placed in a superscript. ISO 10646 defines the NFKC normalization scheme to convert all these into a standard form as well, and GCC warns if your code is not in NFKC if you use -Wnormalized=nfkc. This warning is comparable to warning about every identifier that contains the letter O because it might be confused with the digit 0, and so is not the default, but may be useful as a local coding convention if the programming environment cannot be fixed to display these characters distinctly.
This warning is included in -Wextra. To get other -Wextra warnings without this one, use -Wextra -Wno-override-init.
struct foo { int x; char a, b, c, d; } __attribute__((packed)); struct bar { char z; struct foo f; };
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.
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.
The restrictions on "offsetof" may be relaxed in a future version of the C++ standard.
Note that GCC may optimize small variable-length arrays of a known value into plain arrays, so this warning may not get triggered for such arrays.
This warning is not enabled by -Wall, and is only active when -ftree-vrp is active (default for -O2 and above).
See also -Walloca-larger-than=n.
The limit applies after string constant concatenation, and does not count the trailing NUL. In C90, the limit was 509 characters; in C99, it was raised to 4095. C++98 does not specify a normative minimum maximum, so we do not diagnose overlength strings in C++.
This option is implied by -Wpedantic, and can be disabled with -Wno-overlength-strings.
To tell GCC to emit extra information for use by a debugger, in almost all cases you need only to add -g to your other options.
GCC allows you to use -g with -O. The shortcuts taken by optimized code may occasionally be surprising: 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 are already at hand; some statements may execute in different places because they have been moved out of loops. Nevertheless it is possible to debug optimized output. This makes it reasonable to use the optimizer for programs that might have bugs.
If you are not using some other optimization option, consider using -Og with -g. With no -O option at all, some compiler passes that collect information useful for debugging do not run at all, so that -Og may result in a better debugging experience.
On most systems that use stabs format, -g enables use of extra debugging information that only GDB can use; this extra information makes debugging work better in GDB but probably makes other debuggers crash or refuse to read the program. If you want to control for certain whether to generate the extra information, use -gstabs+, -gstabs, -gxcoff+, -gxcoff, or -gvms (see below).
Note that with DWARF Version 2, some ports require and always use some non-conflicting DWARF 3 extensions in the unwind tables.
Version 4 may require GDB 7.0 and -fvar-tracking-assignments for maximum benefit.
GCC no longer supports DWARF Version 1, which is substantially different than Version 2 and later. For historical reasons, some other DWARF-related options (including -feliminate-dwarf2-dups and -fno-dwarf2-cfi-asm) retain a reference to DWARF Version 2 in their names, but apply to all currently-supported versions of DWARF.
Level 0 produces no debug information at all. Thus, -g0 negates -g.
Level 1 produces minimal information, enough for making backtraces in parts of the program that you don't plan to debug. This includes descriptions of functions and external variables, and line number tables, but no information about local variables.
Level 3 includes extra information, such as all the macro definitions present in the program. Some debuggers support macro expansion when you use -g3.
-gdwarf does not accept a concatenated debug level, to avoid confusion with -gdwarf-level. Instead use an additional -glevel option to change the debug level for DWARF.
It is enabled by default when compiling with optimization (-Os, -O, -O2, ...), debugging information (-g) and the debug info format supports it.
It can be enabled even if var-tracking is disabled, in which case annotations are created and maintained, but discarded at the end. By default, this flag is enabled together with -fvar-tracking, except when selective scheduling is enabled.
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 debug output.
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 debug output.
This option is a detailed version of -femit-struct-debug-reduced and -femit-struct-debug-baseonly, which serves 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 is valid, 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 should 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 when compiling foo.c, debug information is generated for types declared in that file and foo.h, but not other header files. 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 debug output.
These options control various sorts of optimizations.
Without any optimization option, 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 expect from the source code.
Turning on optimization flags makes the compiler attempt to improve the performance and/or code size at the expense of compilation time and possibly the ability to debug the program.
The compiler performs optimization based on the knowledge it has of the program. Compiling multiple files at once to a single output file mode allows the compiler to use information gained from all of the files when compiling each of them.
Not all optimizations are controlled directly by a flag. Only optimizations that have a flag are listed in this section.
Most optimizations are only enabled if an -O level is set on the command line. Otherwise they are disabled, even if individual optimization flags are specified.
Depending on the target and how GCC was configured, a slightly different set of optimizations may be enabled at each -O level than those listed here. You can invoke GCC with -Q --help=optimizers to find out the exact set of optimizations that are enabled at each level.
With -O, the compiler tries to reduce code size and execution time, without performing any optimizations that take a great deal of compilation time.
-O turns on the following optimization flags:
-fauto-inc-dec -fbranch-count-reg -fcombine-stack-adjustments -fcompare-elim -fcprop-registers -fdce -fdefer-pop -fdelayed-branch -fdse -fforward-propagate -fguess-branch-probability -fif-conversion2 -fif-conversion -finline-functions-called-once -fipa-pure-const -fipa-profile -fipa-reference -fmerge-constants -fmove-loop-invariants -freorder-blocks -fshrink-wrap -fshrink-wrap-separate -fsplit-wide-types -fssa-backprop -fssa-phiopt -ftree-bit-ccp -ftree-ccp -ftree-ch -ftree-coalesce-vars -ftree-copy-prop -ftree-dce -ftree-dominator-opts -ftree-dse -ftree-forwprop -ftree-fre -ftree-phiprop -ftree-sink -ftree-slsr -ftree-sra -ftree-pta -ftree-ter -funit-at-a-time
-O also turns on -fomit-frame-pointer on machines where doing so does not interfere with debugging.
-O2 turns on all optimization flags specified by -O. It also turns on the following optimization flags: -fthread-jumps -falign-functions -falign-jumps -falign-loops -falign-labels -fcaller-saves -fcrossjumping -fcse-follow-jumps -fcse-skip-blocks -fdelete-null-pointer-checks -fdevirtualize -fdevirtualize-speculatively -fexpensive-optimizations -fgcse -fgcse-lm -fhoist-adjacent-loads -finline-small-functions -findirect-inlining -fipa-cp -fipa-bit-cp -fipa-vrp -fipa-sra -fipa-icf -fisolate-erroneous-paths-dereference -flra-remat -foptimize-sibling-calls -foptimize-strlen -fpartial-inlining -fpeephole2 -freorder-blocks-algorithm=stc -freorder-blocks-and-partition -freorder-functions -frerun-cse-after-loop -fsched-interblock -fsched-spec -fschedule-insns -fschedule-insns2 -fstore-merging -fstrict-aliasing -fstrict-overflow -ftree-builtin-call-dce -ftree-switch-conversion -ftree-tail-merge -fcode-hoisting -ftree-pre -ftree-vrp -fipa-ra
Please note the warning under -fgcse about invoking -O2 on programs that use computed gotos.
-Os disables the following optimization flags: -falign-functions -falign-jumps -falign-loops -falign-labels -fprefetch-loop-arrays
It also enables -finline-functions, causes the compiler to tune for code size rather than execution speed, and 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 is -fno-foo. In the table below, only one of the forms is listed---the one you typically use. You can figure out the other form by either removing no- or adding it.
The following options control specific optimizations. They are either activated by -O options or are related to ones that are. You can use the following flags in the rare cases when "fine-tuning" of optimizations to be performed is desired.
Disabled at levels -O, -O2, -O3, -Os.
This option is enabled by default at optimization levels -O, -O2, -O3, -Os.
The default is -ffp-contract=fast.
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.
The default setting (when not optimizing for size) for 32-bit GNU/Linux x86 and 32-bit Darwin x86 targets is -fomit-frame-pointer. You can configure GCC with the --enable-frame-pointer configure option to change the default.
Enabled at levels -O, -O2, -O3, -Os.
Enabled at levels -O2, -O3, -Os.
Enabled at levels -O2, -O3.
Single functions can be exempted from inlining by marking them with the "noinline" attribute.
Enabled at level -O2, -O3, -Os.
Enabled at level -O2, -O3, -Os.
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.
Enabled at levels -O3, -Os. Also enabled by -fprofile-use and -fauto-profile.
Enabled at levels -O1, -O2, -O3 and -Os.
Enabled by default.
Enabled at levels -O2, -O3 and -Os.
Inlining is actually controlled by a number of parameters, which may be specified individually by using --param name=value. The -finline-limit=n option sets some of these parameters as follows:
See below for a documentation of the individual parameters controlling inlining and for the defaults of these parameters.
Note: there may be no value to -finline-limit that results in default behavior.
Note: pseudo instruction represents, in this particular context, an abstract measurement of function's size. In no way does it represent a count of assembly instructions and as such its exact meaning might change from one release to an another.
GCC enables this option by default. If you want to force the compiler to check if a variable is referenced, regardless of whether or not optimization is turned on, use the -fno-keep-static-consts option.
This option is the default for optimized compilation if the assembler and linker support it. Use -fno-merge-constants to inhibit this behavior.
Enabled at levels -O, -O2, -O3, -Os.
This option implies -fmerge-constants. In addition to -fmerge-constants this considers e.g. even constant initialized arrays or initialized constant variables with integral or floating-point types. Languages like C or C++ require each variable, including multiple instances of the same variable in recursive calls, to have distinct locations, so using this option results in non-conforming behavior.
Enabled by default at -O1 and higher.
The default is -fbranch-count-reg.
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.
The default is -ffunction-cse
This option turns off this behavior because some programs explicitly rely on variables going to the data section---e.g., so that the resulting executable can find the beginning of that section and/or make assumptions based on that.
The default is -fzero-initialized-in-bss.
Enabled at levels -O2, -O3, -Os.
Enabled at levels -O, -O2, -O3, -Os.
Enabled at levels -O2, -O3, -Os.
Enabled at levels -O2, -O3, -Os.
Enabled at levels -O2, -O3, -Os.
Note: When compiling a program using computed gotos, a GCC extension, you may get better run-time performance if you disable the global common subexpression elimination pass by adding -fno-gcse to the command line.
Enabled at levels -O2, -O3, -Os.
Enabled by default when -fgcse is enabled.
Not enabled at any optimization level.
Not enabled at any optimization level.
Enabled at levels -O2, -O3, -Os.
Enabled at levels -O, -O2, -O3, -Os.
Enabled at levels -O, -O2, -O3, -Os.
Enabled by -Os.
Note however that in some environments this assumption is not true. Use -fno-delete-null-pointer-checks to disable this optimization for programs that depend on that behavior.
This option is enabled by default on most targets. On Nios II ELF, it defaults to off. On AVR and CR16, this option is completely disabled.
Passes that use the dataflow information are enabled independently at different optimization levels.
Enabled at levels -O2, -O3, -Os.
Enabled for Alpha, AArch64 and x86 at levels -O2, -O3, -Os.
This option is enabled at level -Os for all targets.
This option is enabled at level -O3 for some targets.
Enabled at levels -O2, -O3, -Os.
Enabled at levels -O, -O2, -O3, -Os.
Enabled at levels -O2, -O3.
Enabled at levels -O2, -O3, -Os.
This only makes sense when scheduling after register allocation, i.e. with -fschedule-insns2 or at -O2 or higher.
This option is always enabled by default on certain machines, usually those which have no call-preserved registers to use instead.
Enabled at levels -O2, -O3, -Os.
Enabled by default at -O1 and higher.
Enabled at levels -O2, -O3, -Os, however the option is disabled if generated code will be instrumented for profiling (-p, or -pg) or if callee's register usage cannot be known exactly (this happens on targets that do not expose prologues and epilogues in RTL).
Nevertheless the behavior is similar to Gold Linker ICF optimization, GCC ICF works on different levels and thus the optimizations are not same - there are equivalences that are found only by GCC and equivalences found only by Gold.
This flag is enabled by default at -O2 and -Os.
DO I = 1, N A(I) = B(I) + C D(I) = E(I) * F ENDDO
is transformed to
DO I = 1, N A(I) = B(I) + C ENDDO DO I = 1, N D(I) = E(I) * F ENDDO
This pass distributes the initialization loops and generates a call to memset zero. For example, the loop
DO I = 1, N A(I) = 0 B(I) = A(I) + I ENDDO
is transformed to
DO I = 1, N A(I) = 0 ENDDO DO I = 1, N B(I) = A(I) + I ENDDO
and the initialization loop is transformed into a call to memset zero.
A combination of -fweb and CSE is often sufficient to obtain the same effect. However, that is not reliable in cases where the loop body is more complicated than a single basic block. It also does not work at all on some architectures due to restrictions in the CSE pass.
This optimization is enabled by default.
Enabled at level -O2.
This option is enabled at level -O3.
This option may generate better or worse code; results are highly dependent on the structure of loops within the source code.
Disabled at level -Os.
char buf[9]; if (snprintf (buf, "%08x", i) >= sizeof buf) ...
The -fprintf-return-value option relies on other optimizations and yields best results with -O2. It works in tandem with the -Wformat-overflow and -Wformat-truncation options. The -fprintf-return-value option is enabled by default.
-fpeephole is enabled by default. -fpeephole2 enabled at levels -O2, -O3, -Os.
GCC uses heuristics to guess branch probabilities if they are not provided by profiling feedback (-fprofile-arcs). These heuristics are based on the control flow graph. If some branch probabilities are specified by "__builtin_expect", then the heuristics are used to guess branch probabilities for the rest of the control flow graph, taking the "__builtin_expect" info into account. The interactions between the heuristics and "__builtin_expect" can be complex, and in some cases, it may be useful to disable the heuristics so that the effects of "__builtin_expect" are easier to understand.
The default is -fguess-branch-probability at levels -O, -O2, -O3, -Os.
Enabled at levels -O, -O2, -O3, -Os.
The default is simple at levels -O, -Os, and stc at levels -O2, -O3.
This optimization is automatically turned off in the presence of exception handling, for linkonce sections, for functions with a user-defined section attribute and on any architecture that does not support named sections.
Enabled for x86 at levels -O2, -O3.
Also profile feedback must be available to make this option effective. See -fprofile-arcs for details.
Enabled at levels -O2, -O3, -Os.
Pay special attention to code like this:
union a_union { int i; double d; }; int f() { union 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 works as expected. However, this code might not:
int f() { union a_union t; int* ip; t.d = 3.0; ip = &t.i; return *ip; }
Similarly, access by taking the address, casting the resulting pointer and dereferencing the result has undefined behavior, even if the cast uses a union type, e.g.:
int f() { double d = 3.0; return ((union a_union *) &d)->i; }
The -fstrict-aliasing option is enabled at levels -O2, -O3, -Os.
This option also allows the compiler to assume strict pointer semantics: given a pointer to an object, if adding an offset to that pointer does not produce a pointer to the same object, the addition is undefined. This permits the compiler to conclude that "p + u > p" is always true for a pointer "p" and unsigned integer "u". This assumption is only valid because pointer wraparound is undefined, as the expression is false if "p + u" overflows using twos complement arithmetic.
See also the -fwrapv option. Using -fwrapv means that integer signed overflow is fully defined: it wraps. When -fwrapv is used, there is no difference between -fstrict-overflow and -fno-strict-overflow for integers. With -fwrapv certain types of overflow are permitted. For example, if the compiler gets an overflow when doing arithmetic on constants, the overflowed value can still be used with -fwrapv, but not otherwise.
The -fstrict-overflow option is enabled at levels -O2, -O3, -Os.
-fno-align-functions and -falign-functions=1 are equivalent and mean that functions are not aligned.
Some assemblers only support this flag when n is a power of two; in that case, it is rounded up.
If n is not specified or is zero, use a machine-dependent default. The maximum allowed n option value is 65536.
Enabled at levels -O2, -O3.
-fno-align-labels and -falign-labels=1 are equivalent and mean that labels are not aligned.
If -falign-loops or -falign-jumps are applicable and are greater than this value, then their values are used instead.
If n is not specified or is zero, use a machine-dependent default which is very likely to be 1, meaning no alignment. The maximum allowed n option value is 65536.
Enabled at levels -O2, -O3.
-fno-align-loops and -falign-loops=1 are equivalent and mean that loops are not aligned. The maximum allowed n option value is 65536.
If n is not specified or is zero, use a machine-dependent default.
Enabled at levels -O2, -O3.
-fno-align-jumps and -falign-jumps=1 are equivalent and mean that loops are not aligned.
If n is not specified or is zero, use a machine-dependent default. The maximum allowed n option value is 65536.
Enabled at levels -O2, -O3.
Enabled by default.
Enabled at level -O0. When disabled explicitly, it also implies -fno-section-anchors, which is otherwise enabled at -O0 on some targets.
Enabled by default with -funroll-loops.
This option should not be used in combination with -flto. Instead relying on a linker plugin should provide safer and more precise information.
To use the link-time optimizer, -flto and optimization options should be specified at compile time and during the final link. It is recommended that you compile all the files participating in the same link with the same options and also specify those options at link time. For example:
gcc -c -O2 -flto foo.c gcc -c -O2 -flto bar.c gcc -o myprog -flto -O2 foo.o bar.o
The first two invocations to GCC save a bytecode representation of GIMPLE into special ELF sections inside foo.o and bar.o. The final invocation reads the GIMPLE bytecode from foo.o and bar.o, merges the two files into a single internal image, and compiles the result as usual. Since both foo.o and bar.o are merged into a single image, this causes all the interprocedural analyses and optimizations in GCC to work across the two files as if they were a single one. This means, for example, that the inliner is able to inline functions in bar.o into functions in foo.o and vice-versa.
Another (simpler) way to enable link-time optimization is:
gcc -o myprog -flto -O2 foo.c bar.c
The above generates bytecode for foo.c and bar.c, merges them together into a single GIMPLE representation and optimizes them as usual to produce myprog.
The only important thing to keep in mind is that to enable link-time optimizations you need to use the GCC driver to perform the link step. GCC then automatically performs link-time optimization if any of the objects involved were compiled with the -flto command-line option. You generally should specify the optimization options to be used for link-time optimization though GCC tries to be clever at guessing an optimization level to use from the options used at compile time if you fail to specify one at link time. You can always override the automatic decision to do link-time optimization by passing -fno-lto to the link command.
To make whole program optimization effective, it is necessary to make certain whole program assumptions. The compiler needs to know what functions and variables can be accessed by libraries and runtime outside of the link-time optimized unit. When supported by the linker, the linker plugin (see -fuse-linker-plugin) passes information to the compiler about used and externally visible symbols. When the linker plugin is not available, -fwhole-program should be used to allow the compiler to make these assumptions, which leads to more aggressive optimization decisions.
When -fuse-linker-plugin is not enabled, when a file is compiled with -flto, the generated object file is larger than a regular object file because it contains GIMPLE bytecodes and the usual final code (see -ffat-lto-objects. This means that object files with LTO information can be linked as normal object files; if -fno-lto is passed to the linker, no interprocedural optimizations are applied. Note that when -fno-fat-lto-objects is enabled the compile stage is faster but you cannot perform a regular, non-LTO link on them.
Additionally, the optimization flags used to compile individual files are not necessarily related to those used at link time. For instance,
gcc -c -O0 -ffat-lto-objects -flto foo.c gcc -c -O0 -ffat-lto-objects -flto bar.c gcc -o myprog -O3 foo.o bar.o
This produces individual object files with unoptimized assembler code, but the resulting binary myprog is optimized at -O3. If, instead, the final binary is generated with -fno-lto, then myprog is not optimized.
When producing the final binary, GCC only applies link-time optimizations to those files that contain bytecode. Therefore, you can mix and match object files and libraries with GIMPLE bytecodes and final object code. GCC automatically selects which files to optimize in LTO mode and which files to link without further processing.
There are some code generation flags preserved by GCC when generating bytecodes, as they need to be used during the final link stage. Generally options specified at link time override those specified at compile time.
If you do not specify an optimization level option -O at link time, then GCC uses the highest optimization level used when compiling the object files.
Currently, the following options and their settings are taken from the first object file that explicitly specifies them: -fPIC, -fpic, -fpie, -fcommon, -fexceptions, -fnon-call-exceptions, -fgnu-tm and all the -m target flags.
Certain ABI-changing flags are required to match in all compilation units, and trying to override this at link time with a conflicting value is ignored. This includes options such as -freg-struct-return and -fpcc-struct-return.
Other options such as -ffp-contract, -fno-strict-overflow, -fwrapv, -fno-trapv or -fno-strict-aliasing are passed through to the link stage and merged conservatively for conflicting translation units. Specifically -fno-strict-overflow, -fwrapv and -fno-trapv take precedence; and for example -ffp-contract=off takes precedence over -ffp-contract=fast. You can override them at link time.
If LTO encounters objects with C linkage declared with incompatible types in separate translation units to be linked together (undefined behavior according to ISO C99 6.2.7), a non-fatal diagnostic may be issued. The behavior is still undefined at run time. Similar diagnostics may be raised for other languages.
Another feature of LTO is that it is possible to apply interprocedural optimizations on files written in different languages:
gcc -c -flto foo.c g++ -c -flto bar.cc gfortran -c -flto baz.f90 g++ -o myprog -flto -O3 foo.o bar.o baz.o -lgfortran
Notice that the final link is done with g++ to get the C++ runtime libraries and -lgfortran is added to get the Fortran runtime libraries. In general, when mixing languages in LTO mode, you should use the same link command options as when mixing languages in a regular (non-LTO) compilation.
If object files containing GIMPLE bytecode are stored in a library archive, say libfoo.a, it is possible to extract and use them in an LTO link if you are using a linker with plugin support. To create static libraries suitable for LTO, use gcc-ar and gcc-ranlib instead of ar and ranlib; to show the symbols of object files with GIMPLE bytecode, use gcc-nm. Those commands require that ar, ranlib and nm have been compiled with plugin support. At link time, use the the flag -fuse-linker-plugin to ensure that the library participates in the LTO optimization process:
gcc -o myprog -O2 -flto -fuse-linker-plugin a.o b.o -lfoo
With the linker plugin enabled, the linker extracts the needed GIMPLE files from libfoo.a and passes them on to the running GCC to make them part of the aggregated GIMPLE image to be optimized.
If you are not using a linker with plugin support and/or do not enable the linker plugin, then the objects inside libfoo.a are extracted and linked as usual, but they do not participate in the LTO optimization process. In order to make a static library suitable for both LTO optimization and usual linkage, compile its object files with -flto -ffat-lto-objects.
Link-time optimizations do not require the presence of the whole program to operate. If the program does not require any symbols to be exported, it is possible to combine -flto and -fwhole-program to allow the interprocedural optimizers to use more aggressive assumptions which may lead to improved optimization opportunities. Use of -fwhole-program is not needed when linker plugin is active (see -fuse-linker-plugin).
The current implementation of LTO makes no attempt to generate bytecode that is portable between different types of hosts. The bytecode files are versioned and there is a strict version check, so bytecode files generated in one version of GCC do not work with an older or newer version of GCC.
Link-time optimization does not work well with generation of debugging information. Combining -flto with -g is currently experimental and expected to produce unexpected results.
If you specify the optional n, the optimization and code generation done at link time is executed in parallel using n parallel jobs by utilizing an installed make program. The environment variable MAKE may be used to override the program used. The default value for n is 1.
You can also specify -flto=jobserver to use GNU make's job server mode to determine the number of parallel jobs. This is useful when the Makefile calling GCC is already executing in parallel. You must prepend a + to the command recipe in the parent Makefile for this to work. This option likely only works if MAKE is GNU make.
This option enables the extraction of object files with GIMPLE bytecode out of library archives. This improves the quality of optimization by exposing more code to the link-time optimizer. This information specifies what symbols can be accessed externally (by non-LTO object or during dynamic linking). Resulting code quality improvements on binaries (and shared libraries that use hidden visibility) are similar to -fwhole-program. See -flto for a description of the effect of this flag and how to use it.
This option is enabled by default when LTO support in GCC is enabled and GCC was configured for use with a linker supporting plugins (GNU ld 2.21 or newer or gold).
-fno-fat-lto-objects improves compilation time over plain LTO, but requires the complete toolchain to be aware of LTO. It requires a linker with linker plugin support for basic functionality. Additionally, nm, ar and ranlib need to support linker plugins to allow a full-featured build environment (capable of building static libraries etc). GCC provides the gcc-ar, gcc-nm, gcc-ranlib wrappers to pass the right options to these tools. With non fat LTO makefiles need to be modified to use them.
The default is -fno-fat-lto-objects on targets with linker plugin support.
This pass only applies to certain targets that cannot explicitly represent the comparison operation before register allocation is complete.
Enabled at levels -O, -O2, -O3, -Os.
Enabled at levels -O, -O2, -O3, -Os.
Before you can use this option, you must first generate profiling information.
By default, GCC emits an error message if the feedback profiles do not match the source code. This error can be turned into a warning by using -Wcoverage-mismatch. Note this may result in poorly optimized code.
If path is specified, GCC looks at the path to find the profile feedback data files. See -fprofile-dir.
path is the name of a file containing AutoFDO profile information. If omitted, it defaults to fbdata.afdo in the current directory.
Producing an AutoFDO profile data file requires running your program with the perf utility on a supported GNU/Linux target system. For more information, see <https://perf.wiki.kernel.org/>.
E.g.
perf record -e br_inst_retired:near_taken -b -o perf.data \ -- your_program
Then use the create_gcov tool to convert the raw profile data to a format that can be used by GCC. You must also supply the unstripped binary for your program to this tool. See <https://github.com/google/autofdo>.
E.g.
create_gcov --binary=your_program.unstripped --profile=perf.data \ --gcov=profile.afdo
The following options control compiler behavior regarding floating-point arithmetic. These options trade off between speed and correctness. All must be specifically enabled.
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.
-fexcess-precision=standard is not implemented for languages other than C. On the x86, it has no effect if -mfpmath=sse or -mfpmath=sse+387 is specified; in the former case, IEEE semantics apply without excess precision, and in the latter, rounding is unpredictable.
This option causes the preprocessor macro "__FAST_MATH__" to be defined.
This option is not turned on by any -O option besides -Ofast since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications.
This option is not turned on by any -O option since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications.
The default is -fmath-errno.
On Darwin systems, the math library never sets "errno". There is therefore no reason for the compiler to consider the possibility that it might, and -fno-math-errno is the default.
This option is not turned on by any -O option since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications. Enables -fno-signed-zeros, -fno-trapping-math, -fassociative-math and -freciprocal-math.
The default is -fno-unsafe-math-optimizations.
The default is -fno-associative-math.
The default is -fno-reciprocal-math.
This option is not turned on by any -O option since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications.
The default is -fno-finite-math-only.
The default is -fsigned-zeros.
This option should never be turned on by any -O option since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions.
The default is -ftrapping-math.
The default is -fno-rounding-math.
This option is experimental and does not currently guarantee to disable all GCC optimizations that are affected by rounding mode. Future versions of GCC may provide finer control of this setting using C99's "FENV_ACCESS" pragma. This command-line option will be used to specify the default state for "FENV_ACCESS".
This option causes the preprocessor macro "__SUPPORT_SNAN__" to be defined.
The default is -fno-signaling-nans.
This option is experimental and does not currently guarantee to disable all GCC optimizations that affect signaling NaN behavior.
The default is -ffp-int-builtin-inexact, allowing the exception to be raised. This option does nothing unless -ftrapping-math is in effect.
Even if -fno-fp-int-builtin-inexact is used, if the functions generate a call to a library function then the "inexact" exception may be raised if the library implementation does not follow TS 18661.
This option controls the default setting of the ISO C99 "CX_LIMITED_RANGE" pragma. Nevertheless, the option applies to all languages.
The default is -fno-cx-fortran-rules.
The following options control optimizations that may improve performance, but are not enabled by any -O options. This section includes experimental options that may produce broken code.
With -fbranch-probabilities, GCC puts a REG_BR_PROB note on each JUMP_INSN and CALL_INSN. These can be used to improve optimization. Currently, they are only used in one place: in reorg.c, instead of guessing which path a branch is most likely to take, the REG_BR_PROB values are used to exactly determine which path is taken more often.
With -fbranch-probabilities, it reads back the data gathered from profiling values of expressions for usage in optimizations.
Enabled with -fprofile-generate and -fprofile-use.
Enabled with -fprofile-use.
With -fbranch-probabilities, it reads back the data gathered and actually performs the optimizations based on them. Currently the optimizations include specialization of division operations using the knowledge about the value of the denominator.
Enabled by default with -funroll-loops.
Enabled at levels -O2, -O3, -Os.
Enabled with -fprofile-use.
Enabled with -fprofile-use.
Enabled with -O3 and/or -fprofile-use.
Use these options on systems where the linker can perform optimizations to improve locality of reference in the instruction space. Most systems using the ELF object format and SPARC processors running Solaris 2 have linkers with such optimizations. 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 create larger object and executable files and are also slower. You cannot 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.
For example, the implementation of the following function "foo":
static int a, b, c; int foo (void) { return a + b + c; }
usually calculates the addresses of all three variables, but if you compile it with -fsection-anchors, it accesses the variables from a common anchor point instead. The effect is similar to the following pseudocode (which isn't valid C):
int foo (void) { register int *xr = &x; return xr[&a - &x] + xr[&b - &x] + xr[&c - &x]; }
Not all targets support this option.
The names of specific parameters, and the meaning of the values, are tied to the internals of the compiler, and are subject to change without notice in future releases.
In each case, the value is an integer. The allowable choices for name are:
--param max-inline-insns-recursive applies to functions declared inline. For functions not declared inline, recursive inlining happens only when -finline-functions (included in -O3) is enabled; --param max-inline-insns-recursive-auto applies instead. The default value is 450.
--param max-inline-recursive-depth applies to functions declared inline. For functions not declared inline, recursive inlining happens only when -finline-functions (included in -O3) is enabled; --param max-inline-recursive-depth-auto applies instead. The default value is 8.
When profile feedback is available (see -fprofile-generate) the actual recursion depth can be guessed from the probability that function recurses via a given call expression. This parameter limits inlining only to call expressions whose probability exceeds the given threshold (in percents). The default value is 10.
The tracer-dynamic-coverage-feedback parameter is used only when profile feedback is available. The real profiles (as opposed to statically estimated ones) are much less balanced allowing the threshold to be larger value.
Similarly to tracer-dynamic-coverage two parameters are provided. tracer-min-branch-probability-feedback is used for compilation with profile feedback and tracer-min-branch-probability compilation without. The value for compilation with profile feedback needs to be more conservative (higher) in order to make tracer effective.
The default is 30% + 70% * (RAM/1GB) with an upper bound of 100% when RAM >= 1GB. If "getrlimit" is available, the notion of "RAM" is the smallest of actual RAM and "RLIMIT_DATA" or "RLIMIT_AS". If GCC is not able to calculate RAM on a particular platform, the lower bound of 30% is used. Setting this parameter and ggc-min-heapsize to zero causes a full collection to occur at every opportunity. This is extremely slow, but can be useful for debugging.
The default is the smaller of RAM/8, RLIMIT_RSS, or a limit that tries to ensure that RLIMIT_DATA or RLIMIT_AS are not exceeded, but with a lower bound of 4096 (four megabytes) and an upper bound of 131072 (128 megabytes). If GCC is not able to calculate RAM on a particular platform, the lower bound is used. Setting this parameter very large effectively disables garbage collection. Setting this parameter and ggc-min-expand to zero causes a full collection to occur at every opportunity.
The default choice depends on the target.
Note: By default the check is disabled at run time. To enable it, add "detect_stack_use_after_return=1" to the environment variable ASAN_OPTIONS.
GCC supports a number of command-line options that control adding run-time instrumentation to the code it normally generates. For example, one purpose of instrumentation is collect profiling statistics for use in finding program hot spots, code coverage analysis, or profile-guided optimizations. Another class of program instrumentation is adding run-time checking to detect programming errors like invalid pointer dereferences or out-of-bounds array accesses, as well as deliberately hostile attacks such as stack smashing or C++ vtable hijacking. There is also a general hook which can be used to implement other forms of tracing or function-level instrumentation for debug or program analysis purposes.
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).
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.
The following options are enabled: -fprofile-arcs, -fprofile-values, -fvpt.
If path is specified, GCC looks at the path to find the profile feedback data files. See -fprofile-dir.
To optimize the program based on the collected profile information, use -fprofile-use.
Warning: When an application does not properly join all threads (or creates an detached thread), a profile file can be still corrupted.
Using prefer-atomic would be transformed either to atomic, when supported by a target, or to single otherwise. The GCC driver automatically selects prefer-atomic when -pthread is present in the command line.
Note that sanitized atomic builtins cannot throw exceptions when operating on invalid memory addresses with non-call exceptions (-fnon-call-exceptions).
signed char a = SCHAR_MAX; a++;
While -ftrapv causes traps for signed overflows to be emitted, -fsanitize=undefined gives a diagnostic message. This currently works only for the C family of languages.
Currently this feature only works for -fsanitize=undefined (and its suboptions except for -fsanitize=unreachable and -fsanitize=return), -fsanitize=float-cast-overflow, -fsanitize=float-divide-by-zero, -fsanitize=bounds-strict, -fsanitize=kernel-address and -fsanitize=address. For these sanitizers error recovery is turned on by default, except -fsanitize=address, for which this feature is experimental. -fsanitize-recover=all and -fno-sanitize-recover=all is also accepted, the former enables recovery for all sanitizers that support it, the latter disables recovery for all sanitizers that support it.
Even if a recovery mode is turned on the compiler side, it needs to be also enabled on the runtime library side, otherwise the failures are still fatal. The runtime library defaults to "halt_on_error=0" for ThreadSanitizer and UndefinedBehaviorSanitizer, while default value for AddressSanitizer is "halt_on_error=1". This can be overridden through setting the "halt_on_error" flag in the corresponding environment variable.
Syntax without an explicit opts parameter is deprecated. It is equivalent to specifying an opts list of:
undefined,float-cast-overflow,float-divide-by-zero,bounds-strict
Currently there is only an implementation for Intel MPX available, thus x86 GNU/Linux target and -mmpx are required to enable this feature. MPX-based instrumentation requires a runtime library to enable MPX in hardware and handle bounds violation signals. By default when -fcheck-pointer-bounds and -mmpx options are used to link a program, the GCC driver links against the libmpx and libmpxwrappers libraries. Bounds checking on calls to dynamic libraries requires a linker with -z bndplt support; if GCC was configured with a linker without support for this option (including the Gold linker and older versions of ld), a warning is given if you link with -mmpx without also specifying -static, since the overall effectiveness of the bounds checking protection is reduced. See also -static-libmpxwrappers.
MPX-based instrumentation may be used for debugging and also may be included in production code to increase program security. Depending on usage, you may have different requirements for the runtime library. The current version of the MPX runtime library is more oriented for use as a debugging tool. MPX runtime library usage implies -lpthread. See also -static-libmpx. The runtime library behavior can be influenced using various CHKP_RT_* environment variables. See <https://gcc.gnu.org/wiki/Intel%20MPX%20support%20in%20the%20GCC%20compiler> for more details.
Generated instrumentation may be controlled by various -fchkp-* options and by the "bnd_variable_size" structure field attribute and "bnd_legacy", and "bnd_instrument" function attributes. GCC also provides a number of built-in functions for controlling the Pointer Bounds Checker.
Note that this switch does not actually cause checking to be done; the operating system or the language runtime must do that. The switch causes generation of code to ensure that they see the stack being extended.
You can additionally specify a string parameter: no means no checking, generic means force the use of old-style checking, specific means use the best checking method and is equivalent to bare -fstack-check.
Old-style checking is a generic mechanism that requires no specific target support in the compiler but comes with the following drawbacks:
Note that old-style stack checking is also the fallback method for specific if no target support has been added in the compiler.
For instance, if the stack starts at absolute address 0x80000000 and grows downwards, you can use the flags -fstack-limit-symbol=__stack_limit and -Wl,--defsym,__stack_limit=0x7ffe0000 to enforce a stack limit of 128KB. Note that this may only work with the GNU linker.
You can locally override stack limit checking by using the "no_stack_limit" function attribute.
When code compiled with -fsplit-stack calls code compiled without -fsplit-stack, there may not be much stack space available for the latter code to run. If compiling all code, including library code, with -fsplit-stack is not an option, then the linker can fix up these calls so that the code compiled without -fsplit-stack always has a large stack. Support for this is implemented in the gold linker in GNU binutils release 2.21 and later.
This option causes run-time data structures to be built at program startup, which are used for verifying the vtable pointers. The options std and preinit control the timing of when these data structures are built. In both cases the data structures are built before execution reaches "main". Using -fvtable-verify=std causes the data structures to be built after shared libraries have been loaded and initialized. -fvtable-verify=preinit causes them to be built before shared libraries have been loaded and initialized.
If this option appears multiple times in the command line with different values specified, none takes highest priority over both std and preinit; preinit takes priority over std.
Note: This feature appends data to the log file. If you want a fresh log file, be sure to delete any existing one.
Note: This feature appends data to the log files. To get fresh log files, be sure to delete any existing ones.
void __cyg_profile_func_enter (void *this_fn, void *call_site); void __cyg_profile_func_exit (void *this_fn, void *call_site);
The first argument is the address of the start of the current function, which may be looked up exactly in the symbol table.
This instrumentation is also done for functions expanded inline in other functions. The profiling calls indicate where, conceptually, the inline function is entered and exited. This means that addressable versions of such functions must be available. If all your uses of a function are expanded inline, this may mean an additional expansion of code size. If you use "extern inline" in your C code, an addressable version of such functions must be provided. (This is normally the case anyway, but if you get lucky and the optimizer always expands the functions inline, you might have gotten away without providing static copies.)
A function may be given the attribute "no_instrument_function", in which case this instrumentation is not done. This can be used, for example, for the profiling functions listed above, high-priority interrupt routines, and any functions from which the profiling functions cannot safely be called (perhaps signal handlers, if the profiling routines generate output or allocate memory).
For example:
-finstrument-functions-exclude-file-list=/bits/stl,include/sys
excludes any inline function defined in files whose pathnames contain /bits/stl or include/sys.
If, for some reason, you want to include letter , in one of sym, write ,. For example, -finstrument-functions-exclude-file-list=',,tmp' (note the single quote surrounding the option).
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 for actual compilation.
In addition to the options listed here, there are a number of options to control search paths for include files documented in Directory Options. Options to control preprocessor diagnostics are listed in Warning Options.
If you are invoking the preprocessor from a shell or shell-like program you may need to use the shell's quoting syntax to protect characters such as spaces that have a meaning in the shell syntax.
If you wish to define a function-like macro on the command line, write its argument list with surrounding parentheses before the equals sign (if any). Parentheses are meaningful to most shells, so you should quote the option. With sh and csh, -D'name(args...)=definition' works.
-D and -U options are processed in the order they are given on the command line. All -imacros file and -include file options are processed after all -D and -U options.
If multiple -include options are given, the files are included in the order they appear on the command line.
All files specified by -imacros are processed before all files specified by -include.
Unless specified explicitly (with -MT or -MQ), the object file name consists of the name of the source file with any suffix replaced with object file suffix and with any leading directory parts removed. If there are many included files then the rule is split into several lines using \-newline. The rule has no commands.
This option does not suppress the preprocessor's debug output, such as -dM. To avoid mixing such debug output with the dependency rules you should explicitly specify the dependency output file with -MF, or use an environment variable like DEPENDENCIES_OUTPUT. Debug output is still sent to the regular output stream as normal.
Passing -M to the driver implies -E, and suppresses warnings with an implicit -w.
This implies that the choice of angle brackets or double quotes in an #include directive does not in itself determine whether that header appears in -MM dependency output.
When used with the driver options -MD or -MMD, -MF overrides the default dependency output file.
This feature is used in automatic updating of makefiles.
This is typical output:
test.o: test.c test.h test.h:
An -MT option sets the target to be exactly the string you specify. If you want multiple targets, you can specify them as a single argument to -MT, or use multiple -MT options.
For example, -MT '$(objpfx)foo.o' might give
$(objpfx)foo.o: foo.c
$$(objpfx)foo.o: foo.c
The default target is automatically quoted, as if it were given with -MQ.
If -MD is used in conjunction with -E, any -o switch is understood to specify the dependency output file, but if used without -E, each -o is understood to specify a target object file.
Since -E is not implied, -MD can be used to generate a dependency output file as a side-effect of the compilation process.
-fpreprocessed is implicit if the input file has one of the extensions .i, .ii or .mi. These are the extensions that GCC uses for preprocessed files created by -save-temps.
The option's behavior depends on the -E and -fpreprocessed options.
With -E, preprocessing is limited to the handling of directives such as "#define", "#ifdef", and "#error". Other preprocessor operations, such as macro expansion and trigraph conversion are not performed. In addition, the -dD option is implicitly enabled.
With -fpreprocessed, predefinition of command line and most builtin macros is disabled. Macros such as "__LINE__", which are contextually dependent, are handled normally. This enables compilation of files previously preprocessed with "-E -fdirectives-only".
With both -E and -fpreprocessed, the rules for -fpreprocessed take precedence. This enables full preprocessing of files previously preprocessed with "-E -fdirectives-only".
Note that "-ftrack-macro-expansion=2" is activated by default.
This option is off by default, because the resulting preprocessed output is only really suitable as input to GCC. It is switched on by -save-temps.
You should not write this "#pragma" in your own code, but it is safe to edit the filename if the PCH file is available in a different location. The filename may be absolute or it may be relative to GCC's current directory.
You should be prepared for side effects when using -C; it causes the preprocessor to treat comments as tokens in their own right. For example, comments appearing at the start of what would be a directive line have the effect of turning that line into an ordinary source line, since the first token on the line is no longer a #.
In addition to the side-effects of the -C option, the -CC option causes all C++-style comments inside a macro to be converted to C-style comments. This is to prevent later use of that macro from inadvertently commenting out the remainder of the source line.
The -CC option is generally used to support lint comments.
Note that GCC does not otherwise attempt to emulate a pre-standard C compiler, and these options are only supported with the -E switch, or when invoking CPP explicitly.
The nine trigraphs and their replacements are
Trigraph: ??( ??) ??< ??> ??= ??/ ??' ??! ??- Replacement: [ ] { } # \ ^ | ~
By default, GCC ignores trigraphs, but in standard-conforming modes it converts them. See the -std and -ansi options.
touch foo.h; cpp -dM foo.h
shows all the predefined macros.
If you use -dM without the -E option, -dM is interpreted as a synonym for -fdump-rtl-mach.
When used from GCC without -E, this option has no effect.
If you want to pass an option that takes an argument, you must use -Xpreprocessor twice, once for the option and once for the argument.
You can pass options to the assembler.
If you want to pass an option that takes an argument, you must use -Xassembler twice, once for the option and once for the argument.
These options come into play when the compiler links object files into an executable output file. They are meaningless if the compiler is not doing a link step.
It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o. If bar.o refers to functions in z, those functions may not be loaded.
The linker searches a standard list of directories for the library, which is actually a file named liblibrary.a. The linker then uses this file as if it had been specified precisely by name.
The directories searched include several standard system directories plus any that you specify with -L.
Normally the files found this way are library files---archive files whose members are object files. The linker handles an archive file by scanning through it for members which define symbols that have so far been referenced but not defined. But if the file that is found is an ordinary object file, it is linked in the usual fashion. The only difference between using an -l option and specifying a file name is that -l surrounds library with lib and .a and searches several directories.
The compiler may generate calls to "memcmp", "memset", "memcpy" and "memmove". These entries are usually resolved by entries in libc. These entry points should be supplied through some other mechanism when this option is specified.
The compiler may generate calls to "memcmp", "memset", "memcpy" and "memmove". These entries are usually resolved by entries in libc. These entry points should be supplied through some other mechanism when this option is specified.
One of the standard libraries bypassed by -nostdlib and -nodefaultlibs is libgcc.a, a library of internal subroutines which GCC uses to overcome shortcomings of particular machines, or special needs for some languages.
In most cases, you need libgcc.a even when you want to avoid other standard libraries. In other words, when you specify -nostdlib or -nodefaultlibs you should usually specify -lgcc as well. This ensures that you have no unresolved references to internal GCC library subroutines. (An example of such an internal subroutine is "__main", used to ensure C++ constructors are called.)
There are several situations in which an application should use the shared libgcc instead of the static version. The most common of these is when the application wishes to throw and catch exceptions across different shared libraries. In that case, each of the libraries as well as the application itself should use the shared libgcc.
Therefore, the G++ driver automatically adds -shared-libgcc whenever you build a shared library or a main executable, because C++ programs typically use exceptions, so this is the right thing to do.
If, instead, you use the GCC driver to create shared libraries, you may find that they are not always linked with the shared libgcc. If GCC finds, at its configuration time, that you have a non-GNU linker or a GNU linker that does not support option --eh-frame-hdr, it links the shared version of libgcc into shared libraries by default. Otherwise, it takes advantage of the linker and optimizes away the linking with the shared version of libgcc, linking with the static version of libgcc by default. This allows exceptions to propagate through such shared libraries, without incurring relocation costs at library load time.
However, if a library or main executable is supposed to throw or catch exceptions, you must link it using the G++ driver, or using the option -shared-libgcc, such that it is linked with the shared libgcc.
If you want to pass an option that takes a separate argument, you must use -Xlinker twice, once for the option and once for the argument. For example, to pass -assert definitions, you must write -Xlinker -assert -Xlinker definitions. It does not work to write -Xlinker "-assert definitions", because this passes the entire string as a single argument, which is not what the linker expects.
When using the GNU linker, it is usually more convenient to pass arguments to linker options using the option=value syntax than as separate arguments. For example, you can specify -Xlinker -Map=output.map rather than -Xlinker -Map -Xlinker output.map. Other linkers may not support this syntax for command-line options.
These options specify directories to search for header files, for libraries and for parts of the compiler:
Directories specified with -iquote apply only to the quote form of the directive, "#include "file"". Directories specified with -I, -isystem, or -idirafter apply to lookup for both the "#include "file"" and "#include <file>" directives.
You can specify any number or combination of these options on the command line to search for header files in several directories. The lookup order is as follows:
You can use -I to override a system header file, substituting your own version, since these directories are searched before the standard system header file directories. However, you should not use this option to add directories that contain vendor-supplied system header files; use -isystem for that.
The -isystem and -idirafter options also mark the directory as a system directory, so that it gets the same special treatment that is applied to the standard system directories.
If a standard system include directory, or a directory specified with -isystem, is also specified with -I, the -I option is ignored. The directory is still searched but as a system directory at its normal position in the system include chain. This is to ensure that GCC's procedure to fix buggy system headers and the ordering for the "#include_next" directive are not inadvertently changed. If you really need to change the search order for system directories, use the -nostdinc and/or -isystem options.
Any directories specified with -I options before -I- are searched only for headers requested with "#include "file""; they are not searched for "#include <file>". If additional directories are specified with -I options after the -I-, those directories are searched for all #include directives.
In addition, -I- inhibits the use of the directory of the current file directory as the first search directory for "#include "file"". There is no way to override this effect of -I-.
The compiler driver program runs one or more of the subprograms cpp, cc1, as and ld. It tries prefix as a prefix for each program it tries to run, both with and without machine/version/ for the corresponding target machine and compiler version.
For each subprogram to be run, the compiler driver first tries the -B prefix, if any. If that name is not found, or if -B is not specified, the driver tries two standard prefixes, /usr/lib/gcc/ and /usr/local/lib/gcc/. If neither of those results in a file name that is found, the unmodified program name is searched for using the directories specified in your PATH environment variable.
The compiler checks to see if the path provided by -B refers to a directory, and if necessary it adds a directory separator character at the end of the path.
-B prefixes that effectively specify directory names also apply to libraries in the linker, because the compiler translates these options into -L options for the linker. They also apply to include files in the preprocessor, because the compiler translates these options into -isystem options for the preprocessor. In this case, the compiler appends include to the prefix.
The runtime support file libgcc.a can also be searched for using the -B prefix, if needed. If it is not found there, the two standard prefixes above are tried, and that is all. The file is left out of the link if it is not found by those means.
Another way to specify a prefix much like the -B prefix is to use the environment variable GCC_EXEC_PREFIX.
As a special kludge, if the path provided by -B is [dir/]stageN/, where N is a number in the range 0 to 9, then it is replaced by [dir/]include. This is to help with boot-strapping the compiler.
If you use both this option and the -isysroot option, then the --sysroot option applies to libraries, but the -isysroot option applies to header files.
The GNU linker (beginning with version 2.16) has the necessary support for this option. If your linker does not support this option, the header file aspect of --sysroot still works, but the library aspect does not.
These machine-independent options control the interface conventions used in code generation.
Most of them have both positive and negative forms; the negative form of -ffoo is -fno-foo. In the table below, only one of the forms is listed---the one that is not the default. You can figure out the other form by either removing no- or adding it.
For example,
int *p; { int local1; p = &local1; local1 = 10; .... } { int local2; local2 = 20; ... } if (*p == 10) // out of scope use of local1 { }
Another example:
struct A { A(int k) : i(k), j(k) { } int i; int j; }; A *ap; void foo(const A& ar) { ap = &ar; } void bar() { foo(A(10)); // temp object's lifetime ends when foo returns { A a(20); .... } ap->i+= 10; // ap references out of scope temp whose space // is reused with a. What is the value of ap->i? }
The lifetime of a compiler generated temporary is well defined by the C++ standard. When a lifetime of a temporary ends, and if the temporary lives in memory, the optimizing compiler has the freedom to reuse its stack space with other temporaries or scoped local variables whose live range does not overlap with it. However some of the legacy code relies on the behavior of older compilers in which temporaries' stack space is not reused, the aggressive stack reuse can lead to runtime errors. This option is used to control the temporary stack reuse optimization.
The precise convention for returning structures in memory depends on the target configuration macros.
Short structures and unions are those whose size and alignment match that of some integer type.
Warning: code compiled with the -fpcc-struct-return switch is not binary compatible with code compiled with the -freg-struct-return switch. Use it to conform to a non-default application binary interface.
If you specify neither -fpcc-struct-return nor -freg-struct-return, GCC defaults to whichever convention is standard for the target. If there is no standard convention, GCC defaults to -fpcc-struct-return, except on targets where GCC is the principal compiler. In those cases, we can choose the standard, and we chose the more efficient register return alternative.
Warning: code compiled with the -freg-struct-return switch is not binary compatible with code compiled with the -fpcc-struct-return switch. Use it to conform to a non-default application binary interface.
Warning: the -fshort-enums switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface.
Warning: the -fshort-wchar switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface.
Unix C compilers have traditionally allocated storage for uninitialized global variables in a common block. This allows the linker to resolve all tentative definitions of the same variable in different compilation units to the same object, or to a non-tentative definition. This is the behavior specified by -fcommon, and is the default for GCC on most targets. On the other hand, this behavior is not required by ISO C, and on some targets may carry a speed or code size penalty on variable references.
The -fno-common option specifies that the compiler should instead place uninitialized global variables in the data section of the object file. This inhibits the merging of tentative definitions by the linker so you get a multiple-definition error if the same variable is defined in more than one compilation unit. Compiling with -fno-common is useful on targets for which it provides better performance, or if you wish to verify that the program will work on other systems that always treat uninitialized variable definitions this way.
-fno-verbose-asm, the default, causes the extra information to be omitted and is useful when comparing two assembler files.
The added comments include:
For example, given this C source file:
int test (int n) { int i; int total = 0; for (i = 0; i < n; i++) total += i * i; return total; }
compiling to (x86_64) assembly via -S and emitting the result direct to stdout via -o -
gcc -S test.c -fverbose-asm -Os -o -
gives output similar to this:
.file "test.c" # GNU C11 (GCC) version 7.0.0 20160809 (experimental) (x86_64-pc-linux-gnu) [...snip...] # options passed: [...snip...] .text .globl test .type test, @function test: .LFB0: .cfi_startproc # test.c:4: int total = 0; xorl %eax, %eax # <retval> # test.c:6: for (i = 0; i < n; i++) xorl %edx, %edx # i .L2: # test.c:6: for (i = 0; i < n; i++) cmpl %edi, %edx # n, i jge .L5 #, # test.c:7: total += i * i; movl %edx, %ecx # i, tmp92 imull %edx, %ecx # i, tmp92 # test.c:6: for (i = 0; i < n; i++) incl %edx # i # test.c:7: total += i * i; addl %ecx, %eax # tmp92, <retval> jmp .L2 # .L5: # test.c:10: } ret .cfi_endproc .LFE0: .size test, .-test .ident "GCC: (GNU) 7.0.0 20160809 (experimental)" .section .note.GNU-stack,"",@progbits
The comments are intended for humans rather than machines and hence the precise format of the comments is subject to change.
Position-independent code requires special support, and therefore works only on certain machines. For the x86, GCC supports PIC for System V but not for the Sun 386i. Code generated for the IBM RS/6000 is always position-independent.
When this flag is set, the macros "__pic__" and "__PIC__" are defined to 1.
Position-independent code requires special support, and therefore works only on certain machines.
When this flag is set, the macros "__pic__" and "__PIC__" are defined to 2.
-fpie and -fPIE both define the macros "__pie__" and "__PIE__". The macros have the value 1 for -fpie and 2 for -fPIE.
Alternatively, the function attribute "noplt" can be used to avoid calls through the PLT for specific external functions.
In position-dependent code, a few targets also convert calls to functions that are marked to not use the PLT to use the GOT instead.
reg must be the name of a register. The register names accepted are machine-specific and are defined in the "REGISTER_NAMES" macro in the machine description macro file.
This flag does not have a negative form, because it specifies a three-way choice.
It is an error to use this flag with the frame pointer or stack pointer. Use of this flag for other registers that have fixed pervasive roles in the machine's execution model produces disastrous results.
This flag does not have a negative form, because it specifies a three-way choice.
It is an error to use this flag with the frame pointer or stack pointer. Use of this flag for other registers that have fixed pervasive roles in the machine's execution model produces disastrous results.
A different sort of disaster results from the use of this flag for a register in which function values may be returned.
This flag does not have a negative form, because it specifies a three-way choice.
Warning: the -fpack-struct switch causes GCC to generate code that is not binary compatible with code generated without that switch. Additionally, it makes the code suboptimal. Use it to conform to a non-default application binary interface.
Warning: the -fleading-underscore switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface. Not all targets provide complete support for this switch.
The default without -fpic is initial-exec; with -fpic the default is global-dynamic.
A trampoline is a small piece of code that is created at run time on the stack when the address of a nested function is taken, and is used to call the nested function indirectly. Therefore, it requires the stack to be made executable in order for the program to work properly.
-fno-trampolines is enabled by default on a language by language basis to let the compiler avoid generating them, if it computes that this is safe, and replace them with descriptors. Descriptors are made up of data only, but the generated code must be prepared to deal with them. As of this writing, -fno-trampolines is enabled by default only for Ada.
Moreover, code compiled with -ftrampolines and code compiled with -fno-trampolines are not binary compatible if nested functions are present. This option must therefore be used on a program-wide basis and be manipulated with extreme care.
Despite the nomenclature, default always means public; i.e., available to be linked against from outside the shared object. protected and internal are pretty useless in real-world usage so the only other commonly used option is hidden. The default if -fvisibility isn't specified is default, i.e., make every symbol public.
A good explanation of the benefits offered by ensuring ELF symbols have the correct visibility is given by "How To Write Shared Libraries" by Ulrich Drepper (which can be found at <https://www.akkadia.org/drepper/>)---however a superior solution made possible by this option to marking things hidden when the default is public is to make the default hidden and mark things public. This is the norm with DLLs on Windows and with -fvisibility=hidden and "__attribute__ ((visibility("default")))" instead of "__declspec(dllexport)" you get almost identical semantics with identical syntax. This is a great boon to those working with cross-platform projects.
For those adding visibility support to existing code, you may find "#pragma GCC visibility" of use. This works by you enclosing the declarations you wish to set visibility for with (for example) "#pragma GCC visibility push(hidden)" and "#pragma GCC visibility pop". Bear in mind that symbol visibility should be viewed as part of the API interface contract and thus all new code should always specify visibility when it is not the default; i.e., declarations only for use within the local DSO should always be marked explicitly as hidden as so to avoid PLT indirection overheads---making this abundantly clear also aids readability and self-documentation of the code. Note that due to ISO C++ specification requirements, "operator new" and "operator delete" must always be of default visibility.
Be aware that headers from outside your project, in particular system headers and headers from any other library you use, may not be expecting to be compiled with visibility other than the default. You may need to explicitly say "#pragma GCC visibility push(default)" before including any such headers.
"extern" declarations are not affected by -fvisibility, so a lot of code can be recompiled with -fvisibility=hidden with no modifications. However, this means that calls to "extern" functions with no explicit visibility use the PLT, so it is more effective to use "__attribute ((visibility))" and/or "#pragma GCC visibility" to tell the compiler which "extern" declarations should be treated as hidden.
Note that -fvisibility does affect C++ vague linkage entities. This means that, for instance, an exception class that is be thrown between DSOs must be explicitly marked with default visibility so that the type_info nodes are unified between the DSOs.
An overview of these techniques, their benefits and how to use them is at <http://gcc.gnu.org/wiki/Visibility>.
If this option is disabled, the compiler uses the most efficient instruction. In the previous example, that might be a 32-bit load instruction, even though that accesses bytes that do not contain any portion of the bit-field, or memory-mapped registers unrelated to the one being updated.
In some cases, such as when the "packed" attribute is applied to a structure field, it may not be possible to access the field with a single read or write that is correctly aligned for the target machine. In this case GCC falls back to generating multiple accesses rather than code that will fault or truncate the result at run time.
Note: Due to restrictions of the C/C++11 memory model, write accesses are not allowed to touch non bit-field members. It is therefore recommended to define all bits of the field's type as bit-field members.
The default value of this option is determined by the application binary interface for the target processor.
The default value of this option is enabled, thus the only useful form of the option is -fno-sync-libcalls. This option is used in the implementation of the libatomic runtime library.
This section describes command-line options that are primarily of interest to GCC developers, including options to support compiler testing and investigation of compiler bugs and compile-time performance problems. This includes options that produce debug dumps at various points in the compilation; that print statistics such as memory use and execution time; and that print information about GCC's configuration, such as where it searches for libraries. You should rarely need to use any of these options for ordinary compilation and linking tasks.
Some -dletters switches have different meaning 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:
When dumping pretty-printed trees, this option inhibits dumping the bodies of control structures.
When dumping RTL, print the RTL in slim (condensed) form instead of the default LISP-like representation.
This option currently only works for RTL dumps, and the RTL is always dumped in slim form.
gcc -O2 -ftree-vectorize -fdump-tree-vect-blocks=foo.dump -fdump-tree-pre=/dev/stderr file.c
outputs vectorizer dump into foo.dump, while the PRE dump is output on to stderr. If two conflicting dump filenames are given for the same pass, then the latter option overrides the earlier one.
To determine what tree dumps are available or find the dump for a pass of interest follow the steps below.
The options can be divided into two groups: options describing the verbosity of the dump, and options describing which optimizations should be included. The options from both the groups can be freely mixed as they are non-overlapping. However, in case of any conflicts, the later options override the earlier options on the command line.
The following options control the dump verbosity:
One or more of the following option keywords can be used to describe a group of optimizations:
If options is omitted, it defaults to optimized-optall, which means to dump all info about successful optimizations from all the passes.
If the filename is provided, then the dumps from all the applicable optimizations are concatenated into the filename. Otherwise the dump is output onto stderr. Though multiple -fopt-info options are accepted, only one of them can include a filename. If other filenames are provided then all but the first such option are ignored.
Note that the output filename is overwritten in case of multiple translation units. If a combined output from multiple translation units is desired, stderr should be used instead.
In the following example, the optimization info is output to stderr:
gcc -O3 -fopt-info
This example:
gcc -O3 -fopt-info-missed=missed.all
outputs missed optimization report from all the passes into missed.all, and this one:
gcc -O2 -ftree-vectorize -fopt-info-vec-missed
prints information about missed optimization opportunities from vectorization passes on stderr. Note that -fopt-info-vec-missed is equivalent to -fopt-info-missed-vec.
As another example,
gcc -O3 -fopt-info-inline-optimized-missed=inline.txt
outputs information about missed optimizations as well as optimized locations from all the inlining passes into inline.txt.
Finally, consider:
gcc -fopt-info-vec-missed=vec.miss -fopt-info-loop-optimized=loop.opt
Here the two output filenames vec.miss and loop.opt are in conflict since only one output file is allowed. In this case, only the first option takes effect and the subsequent options are ignored. Thus only vec.miss is produced which contains dumps from the vectorizer about missed opportunities.
For n greater than zero, -fsched-verbose outputs the same information as -fdump-rtl-sched1 and -fdump-rtl-sched2. For n greater than one, it also output basic block probabilities, detailed ready list information and unit/insn info. For n greater than two, it includes RTL at abort point, control-flow and regions info. And for n over four, -fsched-verbose also includes dependence info.
Here are some examples showing uses of these options.
# disable ccp1 for all functions -fdisable-tree-ccp1 # disable complete unroll for function whose cgraph node uid is 1 -fenable-tree-cunroll=1 # disable gcse2 for functions at the following ranges [1,1], # [300,400], and [400,1000] # disable gcse2 for functions foo and foo2 -fdisable-rtl-gcse2=foo,foo2 # disable early inlining -fdisable-tree-einline # disable ipa inlining -fdisable-ipa-inline # enable tree full unroll -fenable-tree-unroll
The string can either be a number (decimal, octal or hex) or an arbitrary string (in which case it's converted to a number by computing CRC32).
The string should be different for every file you compile.
When used in combination with the -x command-line option, -save-temps is sensible enough to avoid over writing an input source file with the same extension as an intermediate file. The corresponding intermediate file may be obtained by renaming the source file before using -save-temps.
If you invoke GCC in parallel, compiling several different source files that share a common base name in different subdirectories or the same source file compiled for multiple output destinations, it is likely that the different parallel compilers will interfere with each other, and overwrite the temporary files. For instance:
gcc -save-temps -o outdir1/foo.o indir1/foo.c& gcc -save-temps -o outdir2/foo.o indir2/foo.c&
may result in foo.i and foo.o being written to simultaneously by both compilers.
For example:
gcc -save-temps=obj -c foo.c gcc -save-temps=obj -c bar.c -o dir/xbar.o gcc -save-temps=obj foobar.c -o dir2/yfoobar
creates foo.i, foo.s, dir/xbar.i, dir/xbar.s, dir2/yfoobar.i, dir2/yfoobar.s, and dir2/yfoobar.o.
Without the specification of an output file, the output looks like this:
# cc1 0.12 0.01 # as 0.00 0.01
The first number on each line is the "user time", that is time spent executing the program itself. The second number is "system time", time spent executing operating system routines on behalf of the program. Both numbers are in seconds.
With the specification of an output file, the output is appended to the named file, and it looks like this:
0.12 0.01 cc1 <options> 0.00 0.01 as <options>
The "user time" and the "system time" are moved before the program name, and the options passed to the program are displayed, so that one can later tell what file was being compiled, and with which options.
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 rejects 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.
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.
Disabled by default.
The qualifier "static" means that the function manipulates the stack statically: a fixed number of bytes are allocated for the frame on function entry and released on function exit; no stack adjustments are otherwise made in the function. The second field is this fixed number of bytes.
The qualifier "dynamic" means that the function manipulates the stack dynamically: in addition to the static allocation described above, stack adjustments are made in the body of the function, for example to push/pop arguments around function calls. If the qualifier "bounded" is also present, the amount of these adjustments is bounded at compile time and the second field is an upper bound of the total amount of stack used by the function. If it is not present, the amount of these adjustments is not bounded at compile time and the second field only represents the bounded part.
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`
This is useful when gcc prints the error message installation problem, cannot exec cpp0: No such file or directory. To resolve this you either need to put cpp0 and the other compiler components where gcc expects to find them, or you can set the environment variable GCC_EXEC_PREFIX to the directory where you installed them. Don't forget the trailing /.
Each target machine supported by GCC can have its own options---for example, to allow you to compile for a particular processor variant or ABI, or to control optimizations specific to that machine. By convention, the names of machine-specific options start with -m.
Some configurations of the compiler also support additional target-specific options, usually for compatibility with other compilers on the same platform.
AArch64 Options
These options are defined for AArch64 implementations:
The default depends on the specific target configuration. Note that the LP64 and ILP32 ABIs are not link-compatible; you must compile your entire program with the same ABI, and link with a compatible set of libraries.
The permissible values for arch are armv8-a, armv8.1-a, armv8.2-a, armv8.3-a or native.
The value armv8.3-a implies armv8.2-a and enables compiler support for the ARMv8.3-A architecture extensions.
The value armv8.2-a implies armv8.1-a and enables compiler support for the ARMv8.2-A architecture extensions.
The value armv8.1-a implies armv8-a and enables compiler support for the ARMv8.1-A architecture extension. In particular, it enables the +crc and +lse features.
The value native is available on native AArch64 GNU/Linux and causes the compiler to pick the architecture of the host system. This option has no effect if the compiler is unable to recognize the architecture of the host system,
The permissible values for feature are listed in the sub-section on aarch64-feature-modifiers,,-march and -mcpu Feature Modifiers. Where conflicting feature modifiers are specified, the right-most feature is used.
GCC uses name to determine what kind of instructions it can emit when generating assembly code. If -march is specified without either of -mtune or -mcpu also being specified, the code is tuned to perform well across a range of target processors implementing the target architecture.
The values cortex-a57.cortex-a53, cortex-a72.cortex-a53, cortex-a73.cortex-a35, cortex-a73.cortex-a53 specify that GCC should tune for a big.LITTLE system.
Additionally on native AArch64 GNU/Linux systems the value native tunes performance to the host system. This option has no effect if the compiler is unable to recognize the processor of the host system.
Where none of -mtune=, -mcpu= or -march= are specified, the code is tuned to perform well across a range of target processors.
This option cannot be suffixed by feature modifiers.
GCC uses name to determine what kind of instructions it can emit when generating assembly code (as if by -march) and to determine the target processor for which to tune for performance (as if by -mtune). Where this option is used in conjunction with -march or -mtune, those options take precedence over the appropriate part of this option.
This option is only intended to be useful when developing GCC.
-march and -mcpu Feature Modifiers
Feature modifiers used with -march and -mcpu can be any of the following and their inverses nofeature:
Feature crypto implies simd, which implies fp. Conversely, nofp implies nosimd, which implies nocrypto.
Adapteva Epiphany Options
These -m options are defined for Adapteva Epiphany:
mode can be set to one the following values:
The default is -mfp-mode=caller
ARC Options
The following options control the architecture variant for which code is being compiled:
This option is only available for ARCv2 cores.
The following options are passed through to the assembler, and also define preprocessor macro symbols.
The following options control how the assembly code is annotated:
The following options are passed through to the linker:
The following options control the semantics of generated code:
The following options fine tune code generation:
Due to delay slot scheduling and interactions between operand numbers, literal sizes, instruction lengths, and the support for conditional execution, the target-independent pass to generate conditional execution is often lacking, so the ARC port has kept a special pass around that tries to find more conditional execution generation opportunities after register allocation, branch shortening, and delay slot scheduling have been done. This pass generally, but not always, improves performance and code size, at the cost of extra compilation time, which is why there is an option to switch it off. If you have a problem with call instructions exceeding their allowable offset range because they are conditionalized, you should consider using -mmedium-calls instead.
Enable Local Register Allocation. This is still experimental for ARC, so by default the compiler uses standard reload (i.e. -mno-lra).
This defaults to 3 when -Os is in effect. Otherwise, the behavior when this is not set is equivalent to level 1.
Supported values for cpu are
The following options are maintained for backward compatibility, but are now deprecated and will be removed in a future release:
ARM Options
These -m options are defined for the ARM port:
Specifying soft causes GCC to generate output containing library calls for floating-point operations. softfp allows the generation of code using hardware floating-point instructions, but still uses the soft-float calling conventions. hard allows generation of floating-point instructions and uses FPU-specific calling conventions.
The default depends on the specific target configuration. Note that the hard-float and soft-float ABIs are not link-compatible; you must compile your entire program with the same ABI, and link with a compatible set of libraries.
Architecture revisions older than armv4t are deprecated.
-march=armv6s-m is the armv6-m architecture with support for the (now mandatory) SVC instruction.
-march=armv6zk is an alias for armv6kz, existing for backwards compatibility.
-march=armv7ve is the armv7-a architecture with virtualization extensions.
-march=armv8-a+crc enables code generation for the ARMv8-A architecture together with the optional CRC32 extensions.
-march=armv8.1-a enables compiler support for the ARMv8.1-A architecture. This also enables the features provided by -march=armv8-a+crc.
-march=armv8.2-a enables compiler support for the ARMv8.2-A architecture. This also enables the features provided by -march=armv8.1-a.
-march=armv8.2-a+fp16 enables compiler support for the ARMv8.2-A architecture with the optional FP16 instructions extension. This also enables the features provided by -march=armv8.1-a and implies -mfp16-format=ieee.
-march=native causes the compiler to auto-detect the architecture of the build computer. At present, this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful the option has no effect.
Additionally, this option can specify that GCC should tune the performance of the code for a big.LITTLE system. Permissible names are: cortex-a15.cortex-a7, cortex-a17.cortex-a7, cortex-a57.cortex-a53, cortex-a72.cortex-a53, cortex-a72.cortex-a35, cortex-a73.cortex-a53.
-mtune=generic-arch specifies that GCC should tune the performance for a blend of processors within architecture arch. The aim is to generate code that run well on the current most popular processors, balancing between optimizations that benefit some CPUs in the range, and avoiding performance pitfalls of other CPUs. The effects of this option may change in future GCC versions as CPU models come and go.
-mtune=native causes the compiler to auto-detect the CPU of the build computer. At present, this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful the option has no effect.
Permissible names for this option are the same as those for -mtune.
-mcpu=generic-arch is also permissible, and is equivalent to -march=arch -mtune=generic-arch. See -mtune for more information.
-mcpu=native causes the compiler to auto-detect the CPU of the build computer. At present, this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful the option has no effect.
If -msoft-float is specified this specifies the format of floating-point values.
If the selected floating-point hardware includes the NEON extension (e.g. -mfpu=neon), note that floating-point operations are not generated by GCC's auto-vectorization pass unless -funsafe-math-optimizations is also specified. This is because NEON hardware does not fully implement the IEEE 754 standard for floating-point arithmetic (in particular denormal values are treated as zero), so the use of NEON instructions may lead to a loss of precision.
You can also set the fpu name at function level by using the target("fpu=") function attributes or pragmas.
Specifying a larger number can produce faster, more efficient code, but can also increase the size of the program. Different values are potentially incompatible. Code compiled with one value cannot necessarily expect to work with code or libraries compiled with another value, if they exchange information using structures or unions.
Even if this switch is enabled, not all function calls are turned into long calls. The heuristic is that static functions, functions that have the "short_call" attribute, functions that are inside the scope of a "#pragma no_long_calls" directive, and functions whose definitions have already been compiled within the current compilation unit are not turned into long calls. The exceptions to this rule are that weak function definitions, functions with the "long_call" attribute or the "section" attribute, and functions that are within the scope of a "#pragma long_calls" directive are always turned into long calls.
This feature is not enabled by default. Specifying -mno-long-calls restores the default behavior, as does placing the function calls within the scope of a "#pragma long_calls_off" directive. Note these switches have no effect on how the compiler generates code to handle function calls via function pointers.
t0 .ascii "arm_poke_function_name", 0 .align t1 .word 0xff000000 + (t1 - t0) arm_poke_function_name mov ip, sp stmfd sp!, {fp, ip, lr, pc} sub fp, ip, #4
When performing a stack backtrace, code can inspect the value of "pc" stored at "fp + 0". If the trace function then looks at location "pc - 12" and the top 8 bits are set, then we know that there is a function name embedded immediately preceding this location and has length "((pc[-3]) & 0xff000000)".
You can also override the ARM and Thumb mode for each function by using the target("thumb") and target("arm") function attributes or pragmas.
The ARM attribute "Tag_CPU_unaligned_access" is set in the generated object file to either true or false, depending upon the setting of this option. If unaligned access is enabled then the preprocessor symbol "__ARM_FEATURE_UNALIGNED" is also defined.
AVR Options
These options are defined for AVR implementations:
The default for this option is@tie{}avr2.
GCC supports the following AVR devices and ISAs:
Popping the arguments after the function call can be expensive on AVR so that accumulating the stack space might lead to smaller executables because arguments need not be removed from the stack after such a function call.
This option can lead to reduced code size for functions that perform several calls to functions that get their arguments on the stack like calls to printf-like functions.
Jump relaxing is performed by the linker because jump offsets are not known before code is located. Therefore, the assembler code generated by the compiler is the same, but the instructions in the executable may differ from instructions in the assembler code.
Relaxing must be turned on if linker stubs are needed, see the section on "EIND" and linker stubs below.
This option is used internally by the compiler to select and build multilibs for architectures "avr2" and "avr25". These architectures mix devices with and without "SPH". For any setting other than -mmcu=avr2 or -mmcu=avr25 the compiler driver adds or removes this option from the compiler proper's command line, because the compiler then knows if the device or architecture has an 8-bit stack pointer and thus no "SPH" register or not.
Without this option, the "X" register may be used in the same way as "Y" or "Z" which then is emulated by additional instructions. For example, loading a value with "X+const" addressing with a small non-negative "const < 64" to a register Rn is performed as
adiw r26, const ; X += const ld <Rn>, X ; <Rn> = *X sbiw r26, const ; X -= const
"EIND" and Devices with More Than 128 Ki Bytes of Flash
Pointers in the implementation are 16@tie{}bits wide. The address of a function or label is represented as word address so that indirect jumps and calls can target any code address in the range of 64@tie{}Ki words.
In order to facilitate indirect jump on devices with more than 128@tie{}Ki bytes of program memory space, there is a special function register called "EIND" that serves as most significant part of the target address when "EICALL" or "EIJMP" instructions are used.
Indirect jumps and calls on these devices are handled as follows by the compiler and are subject to some limitations:
#include <avr/io.h> static void __attribute__((section(".init3"),naked,used,no_instrument_function)) init3_set_eind (void) { __asm volatile ("ldi r24,pm_hh8(__trampolines_start)\n\t" "out %i0,r24" :: "n" (&EIND) : "r24","memory"); }
The "__trampolines_start" symbol is defined in the linker script.
LDI r24, lo8(gs(<func>)) LDI r25, hi8(gs(<func>))
int main (void) { /* Call function at word address 0x2 */ return ((int(*)(void)) 0x2)(); }
Instead, a stub has to be set up, i.e. the function has to be called through a symbol ("func_4" in the example):
int main (void) { extern int func_4 (void); /* Call function at byte address 0x4 */ return func_4(); }
and the application be linked with -Wl,--defsym,func_4=0x4. Alternatively, "func_4" can be defined in the linker script.
Handling of the "RAMPD", "RAMPX", "RAMPY" and "RAMPZ" Special Function Registers
Some AVR devices support memories larger than the 64@tie{}KiB range that can be accessed with 16-bit pointers. To access memory locations outside this 64@tie{}KiB range, the content of a "RAMP" register is used as high part of the address: The "X", "Y", "Z" address register is concatenated with the "RAMPX", "RAMPY", "RAMPZ" special function register, respectively, to get a wide address. Similarly, "RAMPD" is used together with direct addressing.
AVR Built-in Macros
GCC defines several built-in macros so that the user code can test for the presence or absence of features. Almost any of the following built-in macros are deduced from device capabilities and thus triggered by the -mmcu= command-line option.
For even more AVR-specific built-in macros see AVR Named Address Spaces and AVR Built-in Functions.
2, 25, 3, 31, 35, 4, 5, 51, 6
for mcu="avr2", "avr25", "avr3", "avr31", "avr35", "avr4", "avr5", "avr51", "avr6",
respectively and
100, 102, 104, 105, 106, 107
for mcu="avrtiny", "avrxmega2", "avrxmega4", "avrxmega5", "avrxmega6", "avrxmega7", respectively. If mcu specifies a device, this built-in macro is set accordingly. For example, with -mmcu=atmega8 the macro is defined to 4.
The built-in macros' names follow the scheme "__AVR_Device__" where Device is the device name as from the AVR user manual. The difference between Device in the built-in macro and device in -mmcu=device is that the latter is always lowercase.
If device is not a device but only a core architecture like avr51, this macro is not defined.
If device is not a device but only a core architecture like avr51, this macro is not defined.
Blackfin Options
The optional sirevision specifies the silicon revision of the target Blackfin processor. Any workarounds available for the targeted silicon revision are enabled. If sirevision is none, no workarounds are enabled. If sirevision is any, all workarounds for the targeted processor are enabled. The "__SILICON_REVISION__" macro is defined to two hexadecimal digits representing the major and minor numbers in the silicon revision. If sirevision is none, the "__SILICON_REVISION__" is not defined. If sirevision is any, the "__SILICON_REVISION__" is defined to be 0xffff. If this optional sirevision is not used, GCC assumes the latest known silicon revision of the targeted Blackfin processor.
GCC defines a preprocessor macro for the specified cpu. For the bfin-elf toolchain, this option causes the hardware BSP provided by libgloss to be linked in if -msim is not given.
Without this option, bf532 is used as the processor by default.
Note that support for bf561 is incomplete. For bf561, only the preprocessor macro is defined.
This feature is not enabled by default. Specifying -mno-long-calls restores the default behavior. Note these switches have no effect on how the compiler generates code to handle function calls via function pointers.
This option can be used with -mcorea or -mcoreb, which selects the one-application-per-core programming model. Without -mcorea or -mcoreb, the single-application/dual-core programming model is used. In this model, the main function of Core B should be named as "coreb_main".
If this option is not used, the single-core application programming model is used.
C6X Options
CRIS Options
These options are defined specifically for the CRIS ports.
CR16 Options
These options are defined specifically for the CR16 ports.
Darwin Options
These options are defined for all architectures running the Darwin operating system.
FSF GCC on Darwin does not create "fat" object files; it creates an object file for the single architecture that GCC was built to target. Apple's GCC on Darwin does create "fat" files if multiple -arch options are used; it does so by running the compiler or linker multiple times and joining the results together with lipo.
The subtype of the file created (like ppc7400 or ppc970 or i686) is determined by the flags that specify the ISA that GCC is targeting, like -mcpu or -march. The -force_cpusubtype_ALL option can be used to override this.
The Darwin tools vary in their behavior when presented with an ISA mismatch. The assembler, as, only permits instructions to be used that are valid for the subtype of the file it is generating, so you cannot put 64-bit instructions in a ppc750 object file. The linker for shared libraries, /usr/bin/libtool, fails and prints an error if asked to create a shared library with a less restrictive subtype than its input files (for instance, trying to put a ppc970 object file in a ppc7400 library). The linker for executables, ld, quietly gives the executable the most restrictive subtype of any of its input files.
A framework directory is a directory with frameworks in it. A framework is a directory with a Headers and/or PrivateHeaders directory contained directly in it that ends in .framework. The name of a framework is the name of this directory excluding the .framework. Headers associated with the framework are found in one of those two directories, with Headers being searched first. A subframework is a framework directory that is in a framework's Frameworks directory. Includes of subframework headers can only appear in a header of a framework that contains the subframework, or in a sibling subframework header. Two subframeworks are siblings if they occur in the same framework. A subframework should not have the same name as a framework; a warning is issued if this is violated. Currently a subframework cannot have subframeworks; in the future, the mechanism may be extended to support this. The standard frameworks can be found in /System/Library/Frameworks and /Library/Frameworks. An example include looks like "#include <Framework/header.h>", where Framework denotes the name of the framework and header.h is found in the PrivateHeaders or Headers directory.
If the compiler was built to use the system's headers by default, then the default for this option is the system version on which the compiler is running, otherwise the default is to make choices that are compatible with as many systems and code bases as possible.
Warning: The -mone-byte-bool switch causes GCC to generate code that is not binary compatible with code generated without that switch. Using this switch may require recompiling all other modules in a program, including system libraries. Use this switch to conform to a non-default data model.
DEC Alpha Options
These -m options are defined for the DEC Alpha implementations:
Note that Alpha implementations without floating-point operations are required to have floating-point registers.
A typical use of this option is building a kernel that does not use, and hence need not save and restore, any floating-point registers.
Other Alpha compilers provide the equivalent options called -scope_safe and -resumption_safe.
Use this option to require GCC to construct all integer constants using code, even if it takes more instructions (the maximum is six).
You typically use this option to build a shared library dynamic loader. Itself a shared library, it must relocate itself in memory before it can find the variables and constants in its own data segment.
The default is -mlarge-data. With this option the data area is limited to just below 2GB. Programs that require more than 2GB of data must use "malloc" or "mmap" to allocate the data in the heap instead of in the program's data segment.
When generating code for shared libraries, -fpic implies -msmall-data and -fPIC implies -mlarge-data.
The default is -mlarge-text.
Supported values for cpu_type are
Native toolchains also support the value native, which selects the best architecture option for the host processor. -mcpu=native has no effect if GCC does not recognize the processor.
Native toolchains also support the value native, which selects the best architecture option for the host processor. -mtune=native has no effect if GCC does not recognize the processor.
Valid options for time are
FR30 Options
These options are defined specifically for the FR30 port.
FT32 Options
These options are defined specifically for the FT32 port.
FRV Options
This switch is mainly for debugging the compiler and will likely be removed in a future version.
This switch is mainly for debugging the compiler and will likely be removed in a future version.
This switch is mainly for debugging the compiler and will likely be removed in a future version.
This switch is mainly for debugging the compiler and will likely be removed in a future version.
This switch is mainly for debugging the compiler and will likely be removed in a future version.
This switch is mainly for debugging the compiler and will likely be removed in a future version.
This switch is mainly for debugging the compiler and will likely be removed in a future version.
This switch is mainly for debugging the compiler and will likely be removed in a future version.
This switch is mainly for debugging the compiler and will likely be removed in a future version.
This switch is mainly for debugging the compiler and will likely be removed in a future version.
This switch is mainly for debugging the compiler and will likely be removed in a future version.
This switch is mainly for debugging the compiler and will likely be removed in a future version.
GNU/Linux Options
These -m options are defined for GNU/Linux targets:
When compiling, this option enables -mbionic, -fPIC, -fno-exceptions and -fno-rtti by default. When linking, this option makes the GCC driver pass Android-specific options to the linker. Finally, this option causes the preprocessor macro "__ANDROID__" to be defined.
H8/300 Options
These -m options are defined for the H8/300 implementations:
HPPA Options
These -m options are defined for the HPPA family of computers:
Such code is suitable for level 0 PA systems and kernels.
This option does not work in the presence of shared libraries or nested functions.
-msoft-float changes the calling convention in the output file; therefore, it is only useful if you compile all of a program with this option. In particular, you need to compile libgcc.a, the library that comes with GCC, with -msoft-float in order for this to work.
Distances are measured from the beginning of functions when using the -ffunction-sections option, or when using the -mgas and -mno-portable-runtime options together under HP-UX with the SOM linker.
It is normally not desirable to use this option as it degrades performance. However, it may be useful in large applications, particularly when partial linking is used to build the application.
The types of long calls used depends on the capabilities of the assembler and linker, and the type of code being generated. The impact on systems that support long absolute calls, and long pic symbol-difference or pc-relative calls should be relatively small. However, an indirect call is used on 32-bit ELF systems in pic code and it is quite long.
-munix=93 provides the same predefines as GCC 3.3 and 3.4. -munix=95 provides additional predefines for "XOPEN_UNIX" and "_XOPEN_SOURCE_EXTENDED", and the startfile unix95.o. -munix=98 provides additional predefines for "_XOPEN_UNIX", "_XOPEN_SOURCE_EXTENDED", "_INCLUDE__STDC_A1_SOURCE" and "_INCLUDE_XOPEN_SOURCE_500", and the startfile unix98.o.
It is important to note that this option changes the interfaces for various library routines. It also affects the operational behavior of the C library. Thus, extreme care is needed in using this option.
Library code that is intended to operate with more than one UNIX standard must test, set and restore the variable "__xpg4_extended_mask" as appropriate. Most GNU software doesn't provide this capability.
On HP-UX 10 and later, the GCC driver adds the necessary options to link with libdld.sl when the -static option is specified. This causes the resulting binary to be dynamic. On the 64-bit port, the linkers generate dynamic binaries by default in any case. The -nolibdld option can be used to prevent the GCC driver from adding these link options.
IA-64 Options
These are the -m options defined for the Intel IA-64 architecture.
LM32 Options
These -m options are defined for the LatticeMico32 architecture:
M32C Options
M32R/D Options
These -m options are defined for Renesas M32R/D architectures:
The addressability of a particular object can be set with the "model" attribute.
The small data area consists of sections ".sdata" and ".sbss". Objects may be explicitly put in the small data area with the "section" attribute using one of these sections.
All modules should be compiled with the same -G num value. Compiling with different values of num may or may not work; if it doesn't the linker gives an error message---incorrect code is not generated.
M680x0 Options
These are the -m options defined for M680x0 and ColdFire processors. The default settings depend on which architecture was selected when the compiler was configured; the defaults for the most common choices are given below.
GCC defines a macro "__mcfarch__" whenever it is generating code for a ColdFire target. The arch in this macro is one of the -march arguments given above.
When used together, -march and -mtune select code that runs on a family of similar processors but that is optimized for a particular microarchitecture.
-mcpu=cpu overrides -march=arch if arch is compatible with cpu. Other combinations of -mcpu and -march are rejected.
GCC defines the macro "__mcf_cpu_cpu" when ColdFire target cpu is selected. It also defines "__mcf_family_family", where the value of family is given by the table above.
You can also use -mtune=68020-40 for code that needs to run relatively well on 68020, 68030 and 68040 targets. -mtune=68020-60 is similar but includes 68060 targets as well. These two options select the same tuning decisions as -m68020-40 and -m68020-60 respectively.
GCC defines the macros "__mcarch" and "__mcarch__" when tuning for 680x0 architecture arch. It also defines "mcarch" unless either -ansi or a non-GNU -std option is used. If GCC is tuning for a range of architectures, as selected by -mtune=68020-40 or -mtune=68020-60, it defines the macros for every architecture in the range.
GCC also defines the macro "__muarch__" when tuning for ColdFire microarchitecture uarch, where uarch is one of the arguments given above.
Use this option for microcontrollers with a 68000 or EC000 core, including the 68008, 68302, 68306, 68307, 68322, 68328 and 68356.
This option inhibits the use of 68881/68882 instructions that have to be emulated by software on the 68040. Use this option if your 68040 does not have code to emulate those instructions.
This option inhibits the use of 68020 and 68881/68882 instructions that have to be emulated by software on the 68060. Use this option if your 68060 does not have code to emulate those instructions.
Use this option for microcontrollers with a CPU32 or CPU32+ core, including the 68330, 68331, 68332, 68333, 68334, 68336, 68340, 68341, 68349 and 68360.
Use this option for microcontroller with a 5200 core, including the MCF5202, MCF5203, MCF5204 and MCF5206.
The option is equivalent to -march=68020 -mtune=68020-40.
The option is equivalent to -march=68020 -mtune=68020-60.
GCC defines the macro "__mcfhwdiv__" when this option is enabled.
This calling convention is incompatible with the one normally used on Unix, so you cannot use it if you need to call libraries compiled with the Unix compiler.
Also, you must provide function prototypes for all functions that take variable numbers of arguments (including "printf"); otherwise incorrect code is generated for calls to those functions.
In addition, seriously incorrect code results if you call a function with too many arguments. (Normally, extra arguments are harmlessly ignored.)
The "rtd" instruction is supported by the 68010, 68020, 68030, 68040, 68060 and CPU32 processors, but not by the 68000 or 5200.
Warning: if you use the -malign-int switch, GCC aligns structures containing the above types differently than most published application binary interface specifications for the m68k.
GCC normally uses a single instruction to load values from the GOT. While this is relatively efficient, it only works if the GOT is smaller than about 64k. Anything larger causes the linker to report an error such as:
relocation truncated to fit: R_68K_GOT16O foobar
If this happens, you should recompile your code with -mxgot. It should then work with very large GOTs. However, code generated with -mxgot is less efficient, since it takes 4 instructions to fetch the value of a global symbol.
Note that some linkers, including newer versions of the GNU linker, can create multiple GOTs and sort GOT entries. If you have such a linker, you should only need to use -mxgot when compiling a single object file that accesses more than 8192 GOT entries. Very few do.
These options have no effect unless GCC is generating position-independent code.
MCore Options
These are the -m options defined for the Motorola M*Core processors.
MeP Options
MicroBlaze Options
Option -xl-mode-app-model is a deprecated alias for -mxl-mode-app-model.
MIPS Options
The native Linux/GNU toolchain also supports the value native, which selects the best architecture option for the host processor. -march=native has no effect if GCC does not recognize the processor.
In processor names, a final 000 can be abbreviated as k (for example, -march=r2k). Prefixes are optional, and vr may be written r.
Names of the form nf2_1 refer to processors with FPUs clocked at half the rate of the core, names of the form nf1_1 refer to processors with FPUs clocked at the same rate as the core, and names of the form nf3_2 refer to processors with FPUs clocked a ratio of 3:2 with respect to the core. For compatibility reasons, nf is accepted as a synonym for nf2_1 while nx and bfx are accepted as synonyms for nf1_1.
GCC defines two macros based on the value of this option. The first is "_MIPS_ARCH", which gives the name of target architecture, as a string. The second has the form "_MIPS_ARCH_foo", where foo is the capitalized value of "_MIPS_ARCH". For example, -march=r2000 sets "_MIPS_ARCH" to "r2000" and defines the macro "_MIPS_ARCH_R2000".
Note that the "_MIPS_ARCH" macro uses the processor names given above. In other words, it has the full prefix and does not abbreviate 000 as k. In the case of from-abi, the macro names the resolved architecture (either "mips1" or "mips3"). It names the default architecture when no -march option is given.
When this option is not used, GCC optimizes for the processor specified by -march. By using -march and -mtune together, it is possible to generate code that runs on a family of processors, but optimize the code for one particular member of that family.
-mtune defines the macros "_MIPS_TUNE" and "_MIPS_TUNE_foo", which work in the same way as the -march ones described above.
MIPS16 code generation can also be controlled on a per-function basis by means of "mips16" and "nomips16" attributes.
For example, code using the standard ISA encoding cannot jump directly to MIPS16 or microMIPS code; it must either use a call or an indirect jump. -minterlink-compressed therefore disables direct jumps unless GCC knows that the target of the jump is not compressed.
Note that the EABI has a 32-bit and a 64-bit variant. GCC normally generates 64-bit code when you select a 64-bit architecture, but you can use -mgp32 to get 32-bit code instead.
For information about the O64 ABI, see <http://gcc.gnu.org/projects/mipso64-abi.html>.
GCC supports a variant of the o32 ABI in which floating-point registers are 64 rather than 32 bits wide. You can select this combination with -mabi=32 -mfp64. This ABI relies on the "mthc1" and "mfhc1" instructions and is therefore only supported for MIPS32R2, MIPS32R3 and MIPS32R5 processors.
The register assignments for arguments and return values remain the same, but each scalar value is passed in a single 64-bit register rather than a pair of 32-bit registers. For example, scalar floating-point values are returned in $f0 only, not a $f0/$f1 pair. The set of call-saved registers also remains the same in that the even-numbered double-precision registers are saved.
Two additional variants of the o32 ABI are supported to enable a transition from 32-bit to 64-bit registers. These are FPXX (-mfpxx) and FP64A (-mfp64 -mno-odd-spreg). The FPXX extension mandates that all code must execute correctly when run using 32-bit or 64-bit registers. The code can be interlinked with either FP32 or FP64, but not both. The FP64A extension is similar to the FP64 extension but forbids the use of odd-numbered single-precision registers. This can be used in conjunction with the "FRE" mode of FPUs in MIPS32R5 processors and allows both FP32 and FP64A code to interlink and run in the same process without changing FPU modes.
All -mabicalls code has traditionally been position-independent, regardless of options like -fPIC and -fpic. However, as an extension, the GNU toolchain allows executables to use absolute accesses for locally-binding symbols. It can also use shorter GP initialization sequences and generate direct calls to locally-defined functions. This mode is selected by -mno-shared.
-mno-shared depends on binutils 2.16 or higher and generates objects that can only be linked by the GNU linker. However, the option does not affect the ABI of the final executable; it only affects the ABI of relocatable objects. Using -mno-shared generally makes executables both smaller and quicker.
-mshared is the default.
You can make -mplt the default by configuring GCC with --with-mips-plt. The default is -mno-plt otherwise.
GCC normally uses a single instruction to load values from the GOT. While this is relatively efficient, it only works if the GOT is smaller than about 64k. Anything larger causes the linker to report an error such as:
relocation truncated to fit: R_MIPS_GOT16 foobar
If this happens, you should recompile your code with -mxgot. This works with very large GOTs, although the code is also less efficient, since it takes three instructions to fetch the value of a global symbol.
Note that some linkers can create multiple GOTs. If you have such a linker, you should only need to use -mxgot when a single object file accesses more than 64k's worth of GOT entries. Very few do.
These options have no effect unless GCC is generating position independent code.
By default or when -mabs=legacy is used the legacy treatment is selected. In this case these instructions are considered arithmetic and avoided where correct operation is required and the input operand might be a NaN. A longer sequence of instructions that manipulate the sign bit of floating-point datum manually is used instead unless the -ffinite-math-only option has also been specified.
The -mabs=2008 option selects the IEEE 754-2008 treatment. In this case these instructions are considered non-arithmetic and therefore operating correctly in all cases, including in particular where the input operand is a NaN. These instructions are therefore always used for the respective operations.
The -mnan=legacy option selects the legacy encoding. In this case quiet NaNs (qNaNs) are denoted by the first bit of their trailing significand field being 0, whereas signaling NaNs (sNaNs) are denoted by the first bit of their trailing significand field being 1.
The -mnan=2008 option selects the IEEE 754-2008 encoding. In this case qNaNs are denoted by the first bit of their trailing significand field being 1, whereas sNaNs are denoted by the first bit of their trailing significand field being 0.
The default is -mnan=legacy unless GCC has been configured with --with-nan=2008.
-mllsc is useful if the runtime environment can emulate the instructions and -mno-llsc can be useful when compiling for nonstandard ISAs. You can make either option the default by configuring GCC with --with-llsc and --without-llsc respectively. --with-llsc is the default for some configurations; see the installation documentation for details.
MicroMIPS code generation can also be controlled on a per-function basis by means of "micromips" and "nomicromips" attributes.
The default size of "int"s, "long"s and pointers depends on the ABI. All the supported ABIs use 32-bit "int"s. The n64 ABI uses 64-bit "long"s, as does the 64-bit EABI; the others use 32-bit "long"s. Pointers are the same size as "long"s, or the same size as integer registers, whichever is smaller.
The default -G option depends on the configuration.
If the linker complains that an application is using too much small data, you might want to try rebuilding the less performance-critical parts with -mno-local-sdata. You might also want to build large libraries with -mno-local-sdata, so that the libraries leave more room for the main program.
If you compile a module Mod with -mextern-sdata -G num -mgpopt, and Mod references a variable Var that is no bigger than num bytes, you must make sure that Var is placed in a small data section. If Var is defined by another module, you must either compile that module with a high-enough -G setting or attach a "section" attribute to Var's definition. If Var is common, you must link the application with a high-enough -G setting.
The easiest way of satisfying these restrictions is to compile and link every module with the same -G option. However, you may wish to build a library that supports several different small data limits. You can do this by compiling the library with the highest supported -G setting and additionally using -mno-extern-sdata to stop the library from making assumptions about externally-defined data.
-mno-gpopt is useful for cases where the $gp register might not hold the value of "_gp". For example, if the code is part of a library that might be used in a boot monitor, programs that call boot monitor routines pass an unknown value in $gp. (In such situations, the boot monitor itself is usually compiled with -G0.)
-mno-gpopt implies -mno-local-sdata and -mno-extern-sdata.
-mexplicit-relocs is the default if GCC was configured to use an assembler that supports relocation operators.
The default is -mcheck-zero-division.
The default is usually -mdivide-traps, but this can be overridden at configure time using --with-divide=breaks. Divide-by-zero checks can be completely disabled using -mno-check-zero-division.
This option has no effect on abicalls code. The default is -mno-long-calls.
On the R8000 CPU when multiply-accumulate instructions are used, the intermediate product is calculated to infinite precision and is not subject to the FCSR Flush to Zero bit. This may be undesirable in some circumstances. On other processors the result is numerically identical to the equivalent computation using separate multiply, add, subtract and negate instructions.
This option can only be used if the target architecture supports branch-likely instructions. -mfix-r10000 is the default when -march=r10000 is used; -mno-fix-r10000 is the default otherwise.
The workarounds for the division errata rely on special functions in libgcc.a. At present, these functions are only provided by the "mips64vr*-elf" configurations.
Other VR4120 errata require a NOP to be inserted between certain pairs of instructions. These errata are handled by the assembler, not by GCC itself.
In common with many processors, the R10K tries to predict the outcome of a conditional branch and speculatively executes inst