[英]Cross-platform code label macro?
在 MSVC & C# 中, #pragma region
可用于标记代码段。
同样,在 GCC/Clang 中, #pragma mark
可以完成同样的事情。
是否可以定义一个宏,例如CODELABEL(label)
,它适用于两个编译器?
基本上,我想避免必须执行以下操作:
#ifdef _WIN32
#pragma region Variables
#else
#pragma mark Variables
#endif
bool MyBool;
int MyInt;
#ifdef _WIN32
#pragma region Methods
#else
#pragma mark Methods
#endif
void MyMethod();
void AnotherMethod();
...相反,请执行以下操作:
CODELABEL( Variables )
bool MyBool;
int MyInt;
CODELABEL( Functions )
void MyMethod();
void AnotherMethod();
这样的事情可能吗?
是的,在 C++11 中,您可以使用_Pragma
,因为不允许在宏定义中使用#pragma
:
#ifdef _WIN32
#define PRAGMA(x) __pragma(x) //it seems like _Pragma isn't supported in MSVC
#else
#define PRAGMA(x) _Pragma(#x)
#endif
#ifdef _WIN32
#define CODELABEL(label) PRAGMA(region label)
#else
#define CODELABEL(label) PRAGMA(mark label)
#endif
PRAGMA
是满足需要字符串文字的_Pragma
,其中两个字符串文字的并排连接(例如, "mark" "section label"
)不起作用。
根据这个主题,以下应该有效。
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
#ifdef _WIN32
#define LABEL region
#else
#define LABEL mark
#endif
进而
#pragma STR(LABEL) Variables
bool MyBool;
int MyInt;
#pragma STR(LABEL) Functions
void MyMethod();
void AnotherMethod();
就 Windows 和 macOS 而言,从 Xcode 12 和 Visual Studio 2019 开始,您可以轻松使用这种在两个平台上都可以正常工作的语法:
#pragma region mark -
#pragma region mark Whathever Your Label
Xcode 默默地忽略“区域”标记,而 VS 将“标记”标记作为标签的一部分,恕我直言,这是一个小问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.