Search code examples
c++buildenvironment-variablesunreal-engine4unreal-engine5

Is it possible to define preprocessor directives for an Unreal project at build time?


I am looking for a way to easily define macros / preprocessor directives at project build/cook time for an Unreal Engine project.

For example, if I want a defined C++ macro MY_BUILDTIME_VAR to be 0 in certain builds, and 1 in others, without having to modify source code every time, in a similar approach to environment varibles in many tools (i.e. NODE_ENV in node.js), or to the command-line approach of i.e. g++ (see here).

I am aware it's possible to define target-wide macros in a project's target.cs with GlobalDefintions.Add("MY_TARGET_VAR=0") or module-wide macros in a module's Build.cs with PublicDefinitions.Add("MY_MODULE_VAR=0"). It helps to have all things defined in one place, but those definitions are still baked in the source file, and can't be changed at build time.

The official documentation mentions several ways of building/cooking an Unreal project with custom parameters, such as the Project Launcher tool and the RunUAT script file. Do any of them allow for build-time macro definitions?

Note: I am not using MS Visual Studio, but JetBrains Rider with .uproject only, so I can't define them in an .sln solution file.


Solution

  • Use an environment variable and read it in your build.cs file. Based on the environment variable set the value of your macro.

    This is a handy utility method I use for this purpose:

    private void AddEnvironmentVariableDefinition(string variableName, string defName, string defaultValue = "0")
    {
        string value = System.Environment.GetEnvironmentVariable(variableName) ?? defaultValue;
        PublicDefinitions.Add(String.Format("{0}={1}", defName, value));
    }