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

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 <[email protected]>
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

You can also install both gcc49 and gcc5 from homebrew/versions:

brew tap homebrew/versions
brew install gcc49 gcc5

You can then refer to them explicitly by gcc-4.9 and gcc-5 (or by exporting environment variables like CC, CXX etc)