Making Xcode 4.2 and Ruby Work Together

As Apple’s LLVM compiler matures, there are fewer reasons for them to continue to maintain their GCC port and its Objective-C extensions. As of Xcode 4.2, Apple no longer includes GCC 4.2, leaving only clang and llvm-gcc.

Unfortunately, there is a large amount of open source software that depends on GNU extensions to the C and C++ languages that clang and llvm-gcc do not (or choose not to) support, including Ruby versions older than 1.9.3 and many of its third party libraries.

Step 1: Get Apple’s vanilla GCC 4.2

One easy way to avoid this problem is to simply downgrade to Xcode 4.1, but this isn’t a terrific solution if you are developing for Mac OS or iOS. Thankfully, Kenneth Reitz has done most of the hard work for us and packaged up GCC installers for Lion and Snow Leopard from Apple’s own GCC source.

After installing his GCC package for Lion, be sure to re-run the Xcode 4.2 installer. If you don’t, you will end up with outdated headers and an older LLVM/Clang toolchain.

Step 2: Configure your shell

Now that you’ve got GCC 4.2, it’s time to make sure that it’s being used to build Ruby. Set these in your shell profile:

export CC=gcc-4.2
export CXX=g++-4.2

Don’t forget to re-source your profile afterwards, or open up a new shell.

Step 3: Ruby

After this, you can proceed with (re-)installing the version of ruby you need, e.g.:

rvm install 1.9.3

If you have recently upgraded to Lion and still have Rubies or gems that were compiled and installed on Snow Leopard, this might be a good time to uninstall and reinstall them. It isn’t strictly necessary, but could help if you end up having segfaults or other strange problems.

Note that this last step is important, as gems like to be compiled with the same compiler that Ruby used. Even if ruby compiled perfectly with clang, some gems may try to use it and fail.

With these steps complete, you should be all ready to get back to doing real work.