Homebrew: how to switch between GCC versions `gcc49` and `gcc`

gcchomebrew

I foolishly uninstalled GCC 4.9 after brew upgradeing to GCC 5. However I need both versions and I need to be able to switch back and forth. I thought I could just do brew switch 4.9.2 but the old version of GCC was installed to the folder Cellar/gcc49/4.9.2 instead of Cellar/gcc/4.9.2, so Homebrew doesn't know where to find the old version.

How can I force Homebrew to install both versions in Cellar/gcc?

That is, I have:

brew list --versions gcc
# gcc 5.1.0
brew list --versions gcc49
# gcc49 4.9.2_1

But I'd like to have:

brew list --versions gcc
# gcc 5.1.0 4.9.2_1

Best Answer

You can’t, those are different formulae, and Homebrew doesn’t allow you to install a previous version of a formula.

The workaround is to remove gcc, then go back in Homebrew’s history (remember that it’s a Git repository), get the gcc formula as it was before the 5.1.0 upgrade, install it, then upgrade gcc to get the latest version.

The 5.1.0 gcc upgrade was done in Homebrew commit 9cf3d4da1148c0a0d2f42c2fbe75f9a557339bab:

$ cd $(brew --prefix)
$ git show -s 9cf3d4da1148c0a0d2f42c2fbe75f9a557339bab
commit 9cf3d4da1148c0a0d2f42c2fbe75f9a557339bab
Author: David Christenson <david@the-david.com>
Date:   Sat May 2 18:58:17 2015 -0600

    gcc 5.1.0

    Update to latest stable release, add option and patch for JIT, remove CLooG dependency,
    refactor language selection, add HEAD, use HTTPS mirror.

You need to checkout the parent commit:

$ git checkout 9cf3d4da1148c0a0d2f42c2fbe75f9a557339bab^

Then get the gcc formula and save it somewhere:

$ brew cat gcc > /tmp/gcc.rb

If you’re lazy I put this formula online here. You can now go Back to the Future:

$ git checkout master

Be sure you removed the current gcc:

$ brew rm gcc

Now install the 4.9 version, either from your local copy:

$ brew install /tmp/gcc.rb

Or from my online copy:

$ brew install https://gist.githubusercontent.com/bfontaine/eacd18e2c413005a7526/raw/320a73fc6e1bbf0009a08e6bd90e9d32c3409007/gcc.rb

You should now have a working GCC 4.9 install. Now, upgrade to get the 5.2:

$ brew upgrade gcc

Done.

$ brew ls --versions gcc
gcc 4.9.2_1 5.2.0