c++compiler-optimizationdebug-symbolscompiler-flagslinker-flags

Improve g++ compiler flags for debug and release


I am making a game in c++ with sdl2, and I am currently compiling the program with g++ using the following flags:

DEBUG_FLAGS = -g -Og -DDEBUG
RELEASE_FLAGS = -O3 -DNDEBUG -mwindows -s

I want the debug build to have as many debug symbols as possible, and I want the release build to sacrifice file size for the most compatibility and performance. I also don't want my class and function names in the release build. Also, I do intend for the game to run on platforms other than windows.

So far, these flags have worked, but I am curious about adding things like -flto, -Wall, -Wextra, -pedantic, and -std=c++17. Also, I am not sure if -DNDEBUG is necessary with -O3, and if -DDEBUG is necessary with -Og.


Solution

  • I have settled on the following flags:

    COMMON_FLAGS = -std=c++17
    WARNING_FLAGS = -Wall -Wextra -Wpedantic -Wformat=2 -Wconversion -Wtrampolines -Wshadow -Wold-style-cast -Woverloaded-virtual -Werror
    DEBUG_FLAGS = -g3 -Og -D_GLIBCXX_ASSERTIONS
    RELEASE_FLAGS = -O3 -DNDEBUG -D_FORTIFY_SOURCE=2 -mwindows -s -flto -fstack-protector-strong
    

    I added -std=c++17 to the common flags to make sure the compiler uses c++ 17.

    I added several warning flags to warn me in case I do something against the standard, and I added -Werror to turn all warnings into errors.

    I also changed -g to -g3 in the debug flags, and changed -DDEBUG (which does nothing with -Og and -g) to -D_GLIBCXX_DEBUG.

    Finally, I added -D_FORTIFY_SOURCE=2 to enable buffer overflow protection, -flto to enable link time optimizations, and -fstack-protector-strong to protect the stack.

    Flag Debug Release Justification
    -std=c++17 x x compatibility
    -Wall x x best practice
    -Wextra x x best practice
    -Wpedantic x x compatibility
    -Wformat=2 x x best practice
    -Wconversion x x best practice
    -Wtrampolines x x best practice
    -Wshadow x x best practice
    -Wold-style-cast x x best practice
    -Woverloaded-virtual x x best practice
    -Werror x x best practice
    -g3 x debugging
    -Og x debugging
    -D_GLIBCXX_DEBUG x debugging
    -O3 x performance
    -DNDEBUG x performance
    -D_FORTIFY_SOURCE=2 x protection
    -mwindows x hide console
    -s x file size
    -flto x performance
    -fstack-protector-strong x protection