Search code examples
xcodepreprocessor

Xcode OTHER_SWIFT_FLAGS vs. SWIFT_ACTIVE_COMPILATION_CONDITIONS vs. Preprocessor Macros (GCC_PREPROCESSOR_DEFINITIONS)


I want to add new directive, for example SUNNY. In order that I can write #if SUNNY ... #endif.

What should I use in Build Settings, why and in which format?

  • Other swift flags
  • Active compilation conditions
  • Preprocessor macros

Now I think that answer is:

Other swift flags - -DSUNNY
Active compilation conditions - SUNNY + $(inherited)
Preprocessor macros - SUNNY=1

,but not sure and don't exactly know why.


Solution

  • If you are using Swift, then use SWIFT_ACTIVE_COMPILATION_CONDITIONS which is "a list of compilation conditions to enable for conditional compilation expressions."

    Only set SUNNY there if SUNNY is true, i.e. if it is 1.

    Reference: https://developer.apple.com/documentation/xcode/build-settings-reference#Active-Compilation-Conditions

    In general, use $(inherited) when you don't want to override existing settings.

    To see how settings are resolved, go to:

    Project Settings (in the Project Navigator click on the Project name at the top which is the name of the xcodeproj file), then Build Settings > Levels.

    Settings inheritance is displayed from right to left. So resolved (in use) settings are overriden or are inherited from Project Settings, then a possible .xcconfig file, then Defaults.

    You can also see resolved settings from: xcodebuild -showBuildSettings from the command line (Terminal app). Such as:

    xcodebuild -configuration Release -showBuildSettings
    

    OTHER_SWIFT_FLAGS is a "list of additional flags to pass to the Swift compiler." Set flags as you have shown, e.g. -DSUNNY.

    Reference: https://developer.apple.com/documentation/xcode/build-settings-reference#Other-Swift-Flags

    ("Preprocessor macros" is a "Setting Title" which refers to the "Setting Name" GCC_PREPROCESSOR_DEFINITIONS. Switch between display of Setting Titles and Setting Names with Xcode menu Editor > Show Setting Names / Titles.)

    GCC_PREPROCESSOR_DEFINITIONS is to set macros (flags / directives) for the clang preprocessor. Set them with a value as you have shown, e.g. SUNNY=1. (When not set the value is interpreted as 0).

    See also: https://developer.apple.com/documentation/xcode/adding-a-build-configuration-file-to-your-project