Stripping Away Unused Code in Preprocessor Based on a Flag Set in Editor for Shipping Builds

Alright, I want to know for certain if it is possible to strip away a block of unused source code for the shipping build, based on a flag that can be set in the editor for an entire UE4 project. I am asking this to figure out if it is possible to:

  1. Avoid unnecessary if checks in packaged game.
  2. Avoid shipping unused blocks of code.

Let’s run this down by an example.

Say, I am writing an actor to calculate its surroundings and react accordingly. And I have two methods for it in my code: one simple and one complex. Let’s say that simple is fast and complex is slow in terms of cpu cycles. I want both methods to be available during development, because I’ll be using complex unless there is a performance issue on the target platform.




class MyActor
{
    Reaction Calculate(Environment env)
    {
#if !WITH_EDITOR && {flag to use Simple}
        return Simple(env);
#elif !WITH_EDITOR && {flag to use Complex}
        return Complex(env);
#else
        if (bUseSimple) // Used in editor in order to determine whether Simple or Complex.
            return Simple(env);
       else
           return Complex(env);
#endif
    }
}



Outside world only sees the function Calculate.

Say you want the same behaviour for the entire project. And you can use the same source code in a different project and change its behaviour by changing the flag.

Note: If there is another way (if there is any) I’d like to learn that as well. Ultimately there shouldn’t be compare instruction in assembly and the behaviour can be set in editor before packaging.

#if UE_BUILD_SHIPPING
// shipping code
#endif

#if UE_BUILD_DEBUG
// debug code
#endif

#if UE_BUILD_DEVELOPMENT
// dev build code
#endif

There is no way to achieve what you want to do - you’re only option is to use the PreProcessors Bruno provided.

Pre-Processors are evaluated by the compiler only. A compiler cannot read runtime values of the program it’s compiling.

The closest thing you’ll get is what Bruno showed, or use newer C++ features like constexpr. Follow this example if you want to add your own defines (“flags”) for your project.