问题
Consider the following function
CGSize CGSizeIntegral(CGSize size)
{
return CGSizeMake(ceilf(size.width), ceilf(size.height));
}
CGSize
actually consists of two CGFloat
s, and CGFloat
's definition changes depending on the architecture:
typedef float CGFloat;// 32-bit
typedef double CGFloat;// 64-bit
So, the above code is wrong on 64-bit systems, and needs to be updated with something like
CGSize CGSizeIntegral(CGSize size)
{
#if 64_bit
return CGSizeMake(ceil(size.width), ceil(size.height));
#else
return CGSizeMake(ceilf(size.width), ceilf(size.height));
#endif
}
There is surely a compiler macro/constant for this (for Mac we can use INTEL_X86
for example) but I haven't been able to find this in the 64-bit transition guide.
How can I determine what architecture is being built for?
回答1:
To determine if you are compiling for 64-bit, use __LP64__
:
#if __LP64__
return CGSizeMake(ceil(size.width), ceil(size.height));
#else
return CGSizeMake(ceilf(size.width), ceilf(size.height));
#endif
__LP64__
stands for "longs and pointers are 64-bit" and is architecture-neutral.
According to your transition guide it applies for iOS as well:
The compiler defines the
__LP64__
macro when compiling for the 64-bit runtime.
However, the preferred way to handle your use case is to use CGFLOAT_IS_DOUBLE
. There is no guarantee that __LP64__
will always mean the CGFloat
is a double, but it would be guaranteed with CGFLOAT_IS_DOUBLE
.
#if CGFLOAT_IS_DOUBLE
return CGSizeMake(ceil(size.width), ceil(size.height));
#else
return CGSizeMake(ceilf(size.width), ceilf(size.height));
#endif
回答2:
For Swift, and neglecting the OP's specific question involving CGFloats, etc., the following may be more swiftish:
#if (arch(i386) || arch(arm))
.... // For 32-bit systems
#else
.... // For 64-bit systems
#endif
#if (arch(x86_64) || arch(arm64))
.... // For 64-bit systems
#endif
On the other hand, the compile-time constants discussed in the above answer are also available in Swift, if they are preferred.
This is mostly copied from here: https://stackoverflow.com/a/24869607/253938
And the Apple docs about these Swift compile-time constants is here: https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html (at the very bottom of the page).
来源:https://stackoverflow.com/questions/18861046/how-to-determine-if-compiling-for-64-bit-ios-in-xcode