How to Fix "mkmf.rb can't find header files for ruby" on Mac OS X Lion

This morning I found myself with the following infuriating error while trying to install the rmagick ruby gem:

Building native extensions. This could take a while… ERROR: Error installing rmagick: ERROR: Failed to build gem native extension.

/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby extconf.rb

mkmf.rb can't find header files for ruby at /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/ruby.h

In fact, I was getting this error for every gem I tried to install which needed to be built “natively”.

Here's how to fix it:

  1. First, make sure you have ImageMagick installed. The easiest way to do this is with Homebrew (this step is only necessary if you're trying to install the rmagick gem. If you're trying to install another gem, you can skip this step.

  2. Then, make sure you've got Xcode 4.1 (or higher) installed from the Mac App Store. It's not enough to simply download it, you need to run the installer found in /Applications/

  3. Then do a sudo gem install rmagick (or whichever gem you were trying).

If you still get the error (as did I) then you probably have your system messed up a bit. I think what caused it for me was having both Xcode 4.1 and Xcode 4.2 (beta) installed. To fix this do the following:

  1. Uninstall Xcode 4.2 with sudo /$DEV_TOOLS_4_2/Library/uninstall-devtools --all where $DEV_TOOLS_4_2 is wherever you installed the Xcode 4.2 beta.

  2. Then do the same for Xcode 4.1 sudo /Developer/Library/uninstall-devtools --all. You might want to restart your system now.

  3. Re-install Xcode 4.1 from the App Store installer.

  4. Install the gem again.

That fixed it for me. I haven't tried installing Xcode 4.2 beta again yet, but I'm guessing this was just some messiness caused by having two Xcode installs. When Xcode 4.2 goes GM (hopefully soon) this should no longer be a problem.

Speed of Light