GCC Flags

Updated at 2014-03-19 10:10

GNU project C/C++ compiler has many flags that will help you to produce good quality or more optimal code. This note has an example that shows how useful stuff you can configure with the flags.

gcc \
    -pipe -m64 -ansi -fPIC -g -O3 -fno-exceptions \
    -fstack-protector -Wl,-z,relro -Wl,-z,now -fvisibility=internal \
    -W -Wall -Wformat-nonliteral -Wformat-security -Wmultichar \
    -Wpointer-arith -Winit-self -Werror -c source.c -o dest.o
Prefer using pipes over temporary files, cleaner way to do it.
Fails the build on systems where assembler cannot write to pipe.

Generate a bit faster code, but disables exceptions.

-fstack-protector -Wl,-z,relro -Wl,-z,now -Wformat-security
Extra protection against memory corruption attacts etc.

Changes the default extern symbol export mode in GCC to internal.

Treat all warnings as errors.

Warn about anything questionable. Enables default warnings:
    -Waddress -Warray-bounds -Wc++0x-compat
    -Wchar-subscripts -Wimplicit-int -Wimplicit-function-declaration
    -Wcomment -Wformat -Wmain
    -Wmissing-braces -Wnonnull -Wparentheses -Wpointer-sign -Wreorder
    -Wreturn-type -Wsequence-point -Wsign-compare (only in C ++ )
    -Wstrict-aliasing -Wstrict-overflow=1 -Wswitch -Wtrigraphs
    -Wuninitialized -Wunknown-pragmas -Wunused-function
    -Wunused-label -Wunused-value -Wunused-variable

Enable warning on format functions e.g. `printf` and `scanf`.

Warn if the format string is not a string literal and so cannot be checked.

Warn about uses of format functions that represent possible security problems

Warn about multicharacter constants e.g. `int waveHeader = 'EVAW';`.
Multicharacter constants have undefined behaviour.

Warn about anything that depends on the `size of` a function type
or of `void`. Also warns when an arithmetic operation involves `NULL`.

Warn when initializing a value with itself e.g. `int i = i`.

Optimize linker.

Discard all local symbols

Disallow having unresolved symbols at link time.

Generate identifier for the build.
The same source with the same flags will generate the same identifier.

Allows more exported symbols with dynamic symbol table.