我如何知道编译器是否启用了ARC支持? [英] How do I know whether the compiler has ARC support enabled?
问题描述
我需要在我的iOS应用程序中编写一个lib。
I need to write a lib in my iOS app.
该语句应该预处理定义为:
The statement should be pre-process define as :
myObject ...
#if ARC
// do nothing
#else
[myObject release]
#endif
或运行时流程:
if (ARC) {
// do nothing
} else {
[myObject release];
}
我该怎么办?
请帮帮我!谢谢。
推荐答案
您可以使用 __ has_feature
,如下所示:
You can use __has_feature
, like so:
#if __has_feature(objc_arc)
// ARC is On
#else
// ARC is Off
#endif
如果你想用GCC构建(Apple的GCC确实如此)不支持ARC),您可能还需要以下内容来确定编译器:
If you want to also build with GCC (Apple's GCC does not support ARC), you may also need the following to determine the compiler:
#if defined(__clang)
// It's Clang
#else
// It's GCC
#endif
更新
综合起来,它们会采用一般形式:
Combined, they would take the general form:
#if defined(__clang)
#if !defined(__has_feature)
// idk when clang introduced this
#error This version of clang does not support __has_feature
#endif
#define MON_IS_ARC_ENABLED_IN_THIS_TRANSLATION __has_feature(objc_arc)
#else
// for every compiler other than clang:
#if defined(__has_feature)
#error Another compiler supports __has_feature
#endif
#define MON_IS_ARC_ENABLED_IN_THIS_TRANSLATION 0
#endif
然后在您的来源中使用 MON_IS_ARC_ENABLED_IN_THIS_TRANSLATION
或进一步 #define
s。
Then just use MON_IS_ARC_ENABLED_IN_THIS_TRANSLATION
in your sources or for further #define
s.
如果您使用的编译器添加支持,则必须为此添加一个案例(并且编译器错误可能会捕获在这种情况下的错误,因为它可能禁止使用ref count ops)。
If a compiler you use adds support, you would have to add a case for that (and compiler errors would likely catch the error in this case, since it would likely forbid use of ref count ops).
请注意,这有额外的检查来证明人们如何(也应该)避免定义保留标识符(基于评论中的对话)。它并非详尽无遗,而是一场演示。如果您发现自己经常编写条件 __ has_feature
检查,则可能需要为此定义一个新宏来减少和简化定义。
Note that this has extra checks to demonstrate how one can (and should) avoid defining reserved identifiers (based on a conversation in the comments). It's not exhaustive, but a demonstration. If you find yourself writing conditional __has_feature
checks often, you may want to define a new macro for that to reduce and simplify definitions.
这篇关于我如何知道编译器是否启用了ARC支持?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!