Xcode allows to define different optimization levels for Debug and Release builds. By default Xcode will not optimize Debug builds at all (-O0
) and it will optimize release builds with -Os
(which is the same as -O2
but optimizations that tend to blow up code size are disabled).
In some cases you have files in an app or framework, that shall be optimized in a different way. E.g. if you have implemented a function that calculates a hash value, you may want this function to be optimized with-O3
or even -Ofast
. Or you’ve written code that is not performance critical at all but it is huge and blows up your binary size, so you would prefer it to be optimized with -Oz
(optimize for smallest code size possible, even if that hurts performance).
You can actually change compile flags per file in Xcode.
- Select the target
- Go to Build Phases
- Open Compile Sources
- Locate the source file
- There’s a “Compiler Flags” column to the very right of the table
- Double click it and add compiler flags that shall only apply to this file
But these settings are then always applied, regardless if Debug or Release build. What if you only want these settings to apply to Release builds, as you can otherwise not debug the code in Debug builds?
This can be achieved by using simple trick. The per file compile flags behave like a build setting in Xcode, so other build settings can be referenced and will be expanded.
Just create a user defined build setting, either for your project or just this target. Go to “Build Settings”, press the +
button left to Basic (+ | Basic
) and select “Add User-Defined Setting”. In older Xcode versions the button was the the very right of the top bar (after Levels, Levels | +
) or you can use the menu (Editor > Add Build Setting > Add User-Defined Setting
).
Name the build setting in any way you wish, e.g. EXTRA_OPTIMIZATION
. As with all settings, this setting can be customized per build configuration. Keep it empty for Debug builds, set it to -O<whatever>
for Release builds.
Now edit the per file compile flags and set them to
$(EXTRA_OPTIMIZATION)
In Debug builds, this expands to nothing, so nothing is changed. In Release builds, this expands to -O<whatever>
.