ruk·si

🔷 C++
GCC Flags

Updated at 2014-03-19 12: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
-pipe
Prefer using pipes over temporary files, cleaner way to do it.
Fails the build on systems where assembler cannot write to pipe.

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

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

-Werror
Treat all warnings as errors.

-Wall
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
    -Wvolatile-register-var

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

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

-Wformat-security
Warn about uses of format functions that represent possible security problems

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

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

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

-Wl,-O1
Optimize linker.

-Wl,--discard-all
Discard all local symbols

-Wl,--no-undefined
Disallow having unresolved symbols at link time.

-Wl,--build-id=sha1
Generate identifier for the build.
The same source with the same flags will generate the same identifier.

-rdynamic
Allows more exported symbols with dynamic symbol table.

Sources