Tuesday, 22 January 2013

Multiple version of gcc on Mac OSX

Sometimes you might find yourself in a situation where you want to run one version of gcc on your Mac while maintaining a previous version, instead of simply upgrading via overwrite. For instance, I have XCode installed (with gcc4.2) but want to compile with gcc4.7. However, if I have problems with XCode using gcc4.7 I want to be able to switch to gcc4.2 on the fly.

First thing to do is install gcc4.7, I will be using MacPorts.

If you want to see what versions of gcc you have at your disposal you can run:
$sudo port search gcc
If you are interested in gaining C++0x/ C++11 functionality you might want to consult http://gcc.gnu.org/projects/cxx0x.html to select a version that suites your needs.

Now to install the new/other version:

$sudo port install gcc47
If I were to see what version of gcc I was running by executing:
$gcc -v
I would see that it still points to a 4.2 version of gcc. What you need to do is "select" the version of gcc you wish to use. You may need to install gcc_select first, but it might already be installed:

$sudo port install gcc_select
To actually select the working version of gcc[1], first see what you have to choose from:
$port select --list gcc
Then make the choice:
$sudo port select --set gcc mp-gcc47 
At this point running gcc (even to display the version number) may result in an error message as such:
gcc-mp-4.7: error trying to exec '/opt/local/bin/i686-apple-darwin10-llvm-gcc-4.2': execvp: No such file or directory
In which case you have to rehash your links[2]. To see if gcc is indeed hashed run:
You will probably see gcc listed in there, rehash gcc's link:
$hash gcc 
Checking the version number of gcc you should see the version you selected as working! In my case gcc4.7 is now working!

[1] http://stackoverflow.com/questions/837992/update-gcc-on-osx 
[2] http://superuser.com/questions/423254/macports-gcc-select-error-trying-to-exec-i686-apple-darwin11-llvm-gcc-4-2