• Uncategorized

About c++ : How-to-build-in-release-mode-with-optimizations-in-GCC

Question Detail

What are the specific options I would need to build in “release mode” with full optimizations in GCC? If there are more than one option, please list them all. Thanks.

Question Answer


There is no ‘one size fits all’ – you need to understand your application, your requirements and the optimisation flags to determine the correct subset for your binary.

Or the answer you want:

Here is a part from a Makefile that I use regularly (in this example, it’s trying to build a program named foo).

If you run it like $ make BUILD=debug or $ make debug
then the Debug CFLAGS will be used. These turn off optimization (-O0) and includes debugging symbols (-g).

If you omit these flags (by running $ make without any additional parameters), you’ll build the Release CFLAGS version where optimization is turned on (-O2), debugging symbols stripped (-s) and assertions disabled (-DNDEBUG).

As others have suggested, you can experiment with different -O* settings dependig on your specific needs.

ifeq ($(BUILD),debug)   
# "Debug" build - no optimization, and debugging symbols
CFLAGS += -O0 -g
# "Release" build - optimization, and no debug symbols

all: foo

    make "BUILD=debug"

foo: foo.o
    # The rest of the makefile comes here...

Note that gcc doesn’t have a “release mode” and a “debug mode” like MSVC does. All code is just code. The presence of the various optimization options (-O2 and -Os are the only ones you generally need to care about unless you’re doing very fine tuning) modifies the generated code, but not in a way to prevent interoperability with other ABI-compliant code. Generally you want optimization on stuff you want to release.

The presence of the “-g” option will cause extended symbol and source code information to be placed in the generated files, which is useful for debugging but increases the size of the file (and reveals your source code), which is something you often don’t want in “released” binaries.

But they’re not exclusive. You can have a binary compiled with optimization and debug info, or one with neither.

-O2 will turn on all optimizations that don’t require a space\speed trade off and tends to be the one I see used most often. -O3 does some space for speed trade offs(like function inline.) -Os does O2 plus does other things to reduce code size. This can make things faster than O3 by improving cache use. (test to find out if it works for you.) Note there are a large number of options that none of the O switches touch. The reason they are left out is because it often depends on what kind of code you are writing or are very architecture dependent.

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.