Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect CPU Architecture (32-bit / 64-bit) runtime in Objective C (Mac OS X)

I'm currently wring a Cocoa application which needs to execute some (console) applications which are optimized for 32 and 64 bit. Because of this I would like to detect what CPU architecture the application is running on so I can start the correct console application.

So in short: how do I detect if the application is running on a 64 bit OS?

Edit: I know about the Mach-O fat binaries, that was not my question. I need to know this so I can start another non bundled (console) application. One that is optimized for x86 and one for x64.

like image 422
Ger Teunis Avatar asked Nov 27 '22 15:11

Ger Teunis


1 Answers

There is a super-easy way. Compile two versions of the executable, one for 32-bit and one for 64-bit and combine them with lipo. That way, the right version will always get executed.

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

Edit: or just compile a universal binary in the first place with gcc -arch i686 -arch x86_64

In response to OP's comment:

if(sizeof(int*) == 4)
    //system is 32-bit
else if(sizeof(int*) == 8)
    //system is 64-bit

EDIT: D'oh! I didn't realise you'd need runtime checking... Going through the output of sysctl -A, two variables look potentially useful. Try parsing the output of sysctl hw.optional.x86_64 and sysctl hw.cpu64bit_capable . I don't have a 32-bit Mac around to test this, but both these are set to 1 in Snow Leopard on a Core2Duo Mac.

like image 164
Chinmay Kanchi Avatar answered Dec 05 '22 12:12

Chinmay Kanchi