Building a Universal Binary from the Command line

The following topic applies to Xcode*.

Consider the following source file, HelloWorld.cpp.

#include <iostream>
using namespace std;
int main() {
  char* platform;
#if defined( __i386__)
  platform = "IA32";
#elif defined(__x86_64__)
  platform = "Intel(R) 64";
#else
  platform = "????";
#endif
 cout << "Hello, " << platform << " World!" << endl;
 return 0;
}

To build a universal binary executable from HelloWorld.cpp:

  1. Initialize the compiler environment by setting the environment variables. You can do this by executing compilervars.sh (or compilervars.csh) with the 'source' command:
    source install-dir/bin/compilervars.sh <arg> where <arg> is ia32 or intel64.

  2. Invoke the compiler with the m32 option and generate the object file, HelloWorld_32:

    icc -m32 -o HelloWorld_32 HelloWorld.cpp  // with EDG compiler
    
    icl -m32 -o HelloWorld_32 HelloWorld.cpp  // with CLANG compiler
    
  3. Invoke the compiler with the m64 option and generate the object file, HelloWorld_64:

    icc -m64 -o HelloWorld_64 HelloWorld.cpp  // with EDG compiler
    
    icl -m64 -o HelloWorld_64 HelloWorld.cpp  // with CLANG compiler
    
  4. Use the lipo utility to create the universal executable, HelloWorld, from the object files, HelloWorld_32 and HelloWorld_64:

    lipo -create -arch i386 HelloWorld_32 -arch x86_64 HelloWorld_64 -output HelloWorld
    

To confirm that your process generates the correct result for both architectures, run the file utility on your universal binary:

file HelloWorld 
HelloWorld: Mach-O universal binary with 2 architectures 
HelloWorld (for architecture i386):Mach-O executable i386 
HelloWorld (for architecture x86_64): Mach-O 64-bit executable  x86_64

Note

The compiler defines the __x86_64__ macro on Intel® 64 architecture only. So, if you execute the universal binary, HelloWorld, on a system based on Intel® 64 architecture, the output is:

Hello, Intel(R) 64 World

On a system based on IA-32 architecture, the output is:

Hello, IA32 World

For more complete information about compiler optimizations, see our Optimization Notice.