有一种超级简单的方法。编译两个版本的可执行文件,一个是32位的,一个是64位的,然后使用lipo将它们组合起来。这样,正确的版本将始终被执行。
gcc -lobjc somefile.m -o somefile -m32 -march=i686
gcc -lobjc somefile.m -o somefile2 -m64 -march=x86_64
lipo -create -arch i686 somefile -arch x86_64 somefile2 -output somefileUniversal
编辑:或者一开始就用 gcc -arch i686 -arch x86_64
编译一个通用二进制文件。
回应楼主的评论:
if(sizeof(int*) == 4)
//system is 32-bit
else if(sizeof(int*) == 8)
//system is 64-bit
编辑:糟糕!我没有意识到您需要运行时检查... 通过运行sysctl -A
的输出,两个变量看起来可能有用。尝试解析sysctl hw.optional.x86_64
和sysctl hw.cpu64bit_capable
的输出。我没有一个32位的Mac来测试这个,但在Core2Duo Mac上的Snow Leopard中这两个都设置为1。
gcc -arch i386 -arch x86_64 somefile.m -o somefileUniversal
:) - Yuji使用[[NSRunningApplication currentApplication] executableArchitecture]
,它会返回以下常量之一:
NSBundleExecutableArchitectureI386
NSBundleExecutableArchitectureX86_64
NSBundleExecutableArchitecturePPC
NSBundleExecutableArchitecturePPC64
例如:
switch ([[NSRunningApplication currentApplication] executableArchitecture]) {
case NSBundleExecutableArchitectureI386:
// TODO: i386
break;
case NSBundleExecutableArchitectureX86_64:
// TODO: x86_64
break;
case NSBundleExecutableArchitecturePPC:
// TODO: ppc
break;
case NSBundleExecutableArchitecturePPC64:
// TODO: ppc64
break;
default:
// TODO: unknown arch
break;
}
arch -32 ...
来运行您的应用程序。如果您想知道 CPU 架构而不考虑正在运行的应用程序的架构,请通过 sysctl 读取 hw.machine
,例如由 bleater 回答的方式。 - Mirek Rusin#if __LP64__
NSString *vExecutablePath = [[NSBundle mainBundle] pathForResource: @"tool64" ofType: @""];
#else
NSString *vExecutablePath = [[NSBundle mainBundle] pathForResource: @"tool32" ofType: @""];
#endif
[NSTask launchedTaskWithLaunchPath: vExecutableName ...];
如果您使用的是Snow Leopard,请使用NSRunningApplication的executableArchitecture。
否则,我会执行以下操作:
-(BOOL) is64Bit
{
#if __LP64__
return YES;
#else
return NO;
#endif
}
编程获取CPU架构名称的字符串:
#include <sys/types.h>
#include <sys/sysctl.h>
// Determine the machine name, e.g. "x86_64".
size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0); // Get size of data to be returned.
char *name = malloc(size);
sysctlbyname("hw.machine", name, &size, NULL, 0);
// Do stuff...
free(name);
在shell脚本中做同样的事情:
set name=`sysctl -n hw.machine`
检查操作系统版本(因此是否为Snow Leopard,64位操作系统)的标准方法详见此处。
lipo -create -arch i386 bin32 -arch x86_64 bin64 -output bin_universal
。 - Yuji