views:

1736

answers:

3

I am developing an Autoconf script for a project which should run on Linux and Mac, 32- and 64-bit. On Linux, detecting 64-bit is easy: you get x86_64 instead of i386 for build_cpu. I can't figure out how to do it for the Mac: both 32- and 64-bit machines give i386 for the build_cpu. Is there a way to detect the difference using Autoconf builtins?

Bonus question: on a 64-bit CPU is there a better way to programmatically detect whether a binary is 32- or 64-bit than the following?

file NAME_OF_BINARY | sed -e 's/.*[^0-9]\([0-9]*\)-bit.*/\1/g'
+1  A: 

To find out which architectures a binary supports, you could use file, you could parse the output of otool -f [name of bin], you could parse the output of lipo -info [name of bin], or you could read the fat file headers yourself (it's a fairly simple and well-documented structure). If you have a single-architecture binary, then otool can tell you about the Mach-O header which tells you which architecture it was compiled for.

No idea what autoconf gives you internally as the host architecture, but as an x86_64 Mac can run x86_64, i386 or ppc7400 binaries, the distinction is somewhat moot. Either compile a universal binary, which is what Apple recommend you do, or look at sysctl hw.optional.x86_64 to determine what box you're on.

Graham Lee
The distinction isn't moot, because I have to match the arch of the installed libraries. sysctl works well.
Chris Conway
A: 

The reason you get i386 for build_cpu is probably because gcc compiles in 32-bit mode by default on Mac OS X, even on 64-bit CPUs. The easiest way to handle this is probably to push it off on the user: if they want a 64-bit binary, they can pass in --build=x86_64-darwin to configure.

Chris Conway
I disagree; the whole point of autoconf is so that you can **avoid** pushing things off on the user.
vy32
There is no automatic way to decide whether a binary should be 32- or 64-bit on an x86-64 architecture. It's fundamentally a question the user has to answer.
Chris Conway
A: 

One thing to keep in mind is that on the Mac, you can compile for multiple architectures, and produce a "universal binary" (formerly known as a "fat binary"). It may be better to simply compile with both -arch i386 -arch x86_64, which will allow the user to choose at runtime which one to run (you can also include -arch ppc -arch ppc64 if you want to support older PPC Macs). That way, if the user ends up moving their filesystem from one machine to another, they will still have appropriate binaries for the given machine. See the 64-bit Transition Guide for more information.

Brian Campbell