OSX fat binaries

Just a little reminder (also to myself)...

Mac OS X support a lot of different processor architectures.
From PPC to Intel, including ARM (for iOS), all of these with 32 or 64 bits instruction sets.

When compiling a C file with GCC under Mac OS X, only the current CPU architecture will be compiled by default.

For instance:

gcc -Wall -o test test.c

Will produce an executable supporting only one architecture (similar to the host machine).

The executable format is called «Mach-O», and is specific to OS X.

The Mach-O format supports more than one architecture.
It means you can have a single binary file, which contain code that will run on different CPU architectures.

Apple introduced that format with Mac OS X, while preparing the transition from the PowerPC architecture to Intel.
The same thing was done for the M68K to PPC transition.
But it's also used to run binaries with 32 or 64 bits instruction sets.

To see what kind of architecture an executable file supports, your can use the «lipo» command.
For instance, on my computer (Intel x86_64):

lipo -info /bin/bash

will return:

Architectures in the fat file: /bin/bash are: x86_64 i386

Meaning the executable can be run on Intel 64bits or 32bits processors.

In order to compile an executable for a specific processor architecture, you can pass the -arch option to GCC.
For instance, to compile a FAT binary, that will run on 64 and 64 bits intel processors:

gcc -Wall -arch x86_64 -arch i386 -o test test.c