COMPILED_PLATFORM_HEADER

在 UE4.22 之前,UE 的跨平台库的实现方式都是创建一个泛型平台类:

1
2
3
4
struct FGenericPlatformUtils
{
static void GenericMethod(){}
};

然后每个平台实现:

1
2
3
4
5
6
7
8
// Windows/WindowsPlatformUtils.h
struct FWindowsPlatformUtils:public FGenericPlatformUtils
{
static void GenericMethod(){
//doSomething...
}
};
typedef FWindowsPlatformUtils FPlatformUtils;

在 UE4.22 之前,需要使用下面这种方法:

1
2
3
4
5
6
7
8
9
10
// PlatformUtils.h
#if PLATFORM_ANDROID
#include "Android/AndroidPlatformUtils.h"
#elif PLATFORM_IOS
#include "IOS/IOSPlatformUtils.h"
#elif PLATFORM_WINDOWS
#include "Windows/WindowsPlatformUtils.h"
#elif PLATFORM_MAC
#include "Mac/MacPlatformUtils.h"
#endif

需要手动判断每个平台再进行包含,也是比较麻烦的,在 4.23 之后,UE 引入了一个宏:COMPILED_PLATFORM_HEADER,可以把上面的包含简化为下面的代码:

1
#include COMPILED_PLATFORM_HEADER(PlatformUtils.h)

它是定义在 Runtime/Core/Public/HAL/PreprocessorHelpers.h 下的宏:

1
2
3
4
5
6
7
#if PLATFORM_IS_EXTENSION
// Creates a string that can be used to include a header in the platform extension form "PlatformHeader.h", not like below form
#define COMPILED_PLATFORM_HEADER(Suffix) PREPROCESSOR_TO_STRING(PREPROCESSOR_JOIN(PLATFORM_HEADER_NAME, Suffix))
#else
// Creates a string that can be used to include a header in the form "Platform/PlatformHeader.h", like "Windows/WindowsPlatformFile.h"
#define COMPILED_PLATFORM_HEADER(Suffix) PREPROCESSOR_TO_STRING(PREPROCESSOR_JOIN(PLATFORM_HEADER_NAME/PLATFORM_HEADER_NAME, Suffix))
#endif

注释已经比较说明作用了。而且它还有兄弟宏:

1
2
3
4
5
6
7
#if PLATFORM_IS_EXTENSION
// Creates a string that can be used to include a header with the platform in its name, like "Pre/Fix/PlatformNameSuffix.h"
#define COMPILED_PLATFORM_HEADER_WITH_PREFIX(Prefix, Suffix) PREPROCESSOR_TO_STRING(Prefix/PREPROCESSOR_JOIN(PLATFORM_HEADER_NAME, Suffix))
#else
// Creates a string that can be used to include a header with the platform in its name, like "Pre/Fix/PlatformName/PlatformNameSuffix.h"
#define COMPILED_PLATFORM_HEADER_WITH_PREFIX(Prefix, Suffix) PREPROCESSOR_TO_STRING(Prefix/PLATFORM_HEADER_NAME/PREPROCESSOR_JOIN(PLATFORM_HEADER_NAME, Suffix))
#endif

命名有规律是多么重要的一件事…