[英]C++/C Code to have different execution block on M1 and Intel
I am writing a code for macOS application.我正在为 macOS 应用程序编写代码。 The application would be running on M1 based Macs as well as Intel based Macs also.
该应用程序将在基于 M1 的 Mac 以及基于 Intel 的 Mac 上运行。 What would be the switch to differentiate M1 and Intel?
什么是区分 M1 和英特尔的开关?
if (M1)
{
do something for M1
}
else if (Intel)
{
do something for Intel
}
I was just fooling around with this and found this reference for Objective-C from apple that seemed to work with clang for C++.我只是在玩这个,发现这个来自苹果的 Objective-C 的参考似乎适用于 clang 的 C++。
// Objective-C example
#include "TargetConditionals.h"
#if TARGET_OS_OSX
// Put CPU-independent macOS code here.
#if TARGET_CPU_ARM64
// Put 64-bit Apple silicon macOS code here.
#elif TARGET_CPU_X86_64
// Put 64-bit Intel macOS code here.
#endif
#elif TARGET_OS_MACCATALYST
// Put Mac Catalyst-specific code here.
#elif TARGET_OS_IOS
// Put iOS-specific code here.
#endif
https://developer.apple.com/documentation/apple-silicon/building-a-universal-macos-binary https://developer.apple.com/documentation/apple-silicon/building-a-universal-macos-binary
I specifically checked to see if TARGET_CPU_ARM64
was defined in my header.我专门检查了我的 header 中是否定义了
TARGET_CPU_ARM64
。
Hopefully this helps someone.希望这可以帮助某人。
If you need a runtime check instead of compile time check, you can think of using something like below如果您需要运行时检查而不是编译时检查,您可以考虑使用以下内容
#include <sys/sysctl.h>
#include <mach/machine.h>
int main(int argc, const char * argv[])
{
cpu_type_t type;
size_t size = sizeof(type);
sysctlbyname("hw.cputype", &type, &size, NULL, 0);
int procTranslated;
size = sizeof(procTranslated);
// Checks whether process is translated by Rosetta
sysctlbyname("sysctl.proc_translated", &procTranslated, &size, NULL, 0);
// Removes CPU_ARCH_ABI64 or CPU_ARCH_ABI64_32 encoded with the Type
cpu_type_t typeWithABIInfoRemoved = type & ~CPU_ARCH_MASK;
if (typeWithABIInfoRemoved == CPU_TYPE_X86)
{
if (procTranslated == 1)
{
cout << "ARM Processor (Running x86 application in Rosetta)";
}
else
{
cout << "Intel Processor";
}
}
else if (typeWithABIInfoRemoved == CPU_TYPE_ARM)
{
cout << "ARM Processor";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.