How to set preprocessor macro based on Project Settings variable?

Hi there! I’m wondering how I would go about defining a macro based on the value of a variable in my project settings?

Specifically, I’m working on a plugin for an inventory system and I’d like to define some macros that will compile/exclude certain parts of the code based on the type of inventory system I want (of which there are two “types” right now). I have a custom project settings category implemented with a single boolean variable. I’d like that boolean variable to be used to define a macro, such as INVENTORY_TYPE_SLOT, so that I can compile/exclude what I need.

For example it’d look something like this:


// In MyProjectSettings.h
bool bToggleInventorySystemType;

// In WhereverTheHellI'dDefineMyMacros.something
#define INVENTORY_TYPE_SLOT bToggleInventorySystemType
#define INVENTORY_TYPE_LIST !bToggleInventorySystemType

There very well could be alternate solutions to what I’m trying to do (I don’t want to do if/else conditions with the variable though since that still compiles all the code), but if you have any ideas how I could do what I described above I’d love to hear it.

Additionally, would there be any important differences from the solution to the former problem and defining a macro from an enum or int? I suspect not, but honestly I don’t really know as I’ve never tried something like this.

You should look into how to use the C++ Preprocessor :slight_smile:

What you want to do to completely compile something out conditionally, is



#define USE_FEATURE_ONE
...
#ifdef USE_FEATURE_ONE
code that implements "feature one"
#endif
...
#ifdef USE_FEATURE_TWO
code that implements "feature two"
#endif


now, what you can’t do, is connect a run-time variable (bool bToggleInventorySystemType) to a pre-processor macro – the game doesn’t exist at build time. If you want to compile it all out, you have to do it with a #define

Setting preprocessor defines conditionally like that needs to be done in the module’s build.cs file. For example, from the Steam controller plugin:

bool bSteamSDKFound = Directory.Exists(Target.UEThirdPartySourceDirectory + "Steamworks/" + SteamVersion) == true;
PublicDefinitions.Add("STEAMSDK_FOUND=" + (bSteamSDKFound ? "1" : "0"));

You can read config files using ConfigCache.ReadHierarchy(), you can see an example in Engine\Plugins\Lumin\MagicLeap\Source\MLSDK\MLSDK.Build.cs

2 Likes

good point! still not a setting in game, but I completely failed to consider the build.cs system. I’m still pretty new to this.