Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

iphone - How do I know whether the compiler has ARC support enabled?

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

or run-time process as:

if (ARC) {
   // do nothing
} else {
   [myObject release];
}

How can I do?

Please help me! Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use __has_feature, like so:

#if __has_feature(objc_arc)
// ARC is On
#else
// ARC is Off
#endif

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

Update

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

Then just use MON_IS_ARC_ENABLED_IN_THIS_TRANSLATION in your sources or for further #defines.

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).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...