GCC Compiler – Setting GCC 4.8 as Default on macOS with Xcode and Homebrew

gcchomebrewmacosxcode

I recently installed gcc 4.8 using brew on OSX 10.7.5 (Lion). I can now compile using gcc 4.8 by using

g++-4.8 some_file.c

or using the default gcc 4.2 by using

g++ some_file.c

I want to use gcc 4.8 as the default compiler for Xcode and if I type gcc at the terminal. I suppose I must alter gcc-related links within dirname $(which gcc).

When I do

ls -al $(dirname $(which gcc)) | grep 'gcc\|g++\|c++'

I get the following:

lrwxr-xr-x     1 root   wheel         7 Jul 31 12:17 c++ -> clang++
-rwxr-xr-x     1 root   wheel    909360 Nov 18  2011 c++filt
lrwxr-xr-x     1 root   wheel         5 Jul 31 12:17 clang++ -> clang
lrwxr-xr-x     1 root   wheel        12 Jul 31 12:17 g++ -> llvm-g++-4.2
lrwxr-xr-x     1 root   wheel        12 Jul 31 12:17 gcc -> llvm-gcc-4.2
lrwxr-xr-x     1 root   wheel        28 Jul 31 12:17 gcov-4.2 -> ../llvm-gcc-4.2/bin/gcov-4.2
lrwxr-xr-x     1 root   wheel        52 Jul 31 12:17 i686-apple-darwin11-llvm-g++-4.2 -> ../llvm-gcc-4.2/bin/i686-apple-darwin11-llvm-g++-4.2
lrwxr-xr-x     1 root   wheel        52 Jul 31 12:17 i686-apple-darwin11-llvm-gcc-4.2 -> ../llvm-gcc-4.2/bin/i686-apple-darwin11-llvm-gcc-4.2
lrwxr-xr-x     1 root   wheel        32 Jul 31 12:17 llvm-cpp-4.2 -> ../llvm-gcc-4.2/bin/llvm-cpp-4.2
lrwxr-xr-x     1 root   wheel        32 Jul 31 12:17 llvm-g++ -> ../llvm-gcc-4.2/bin/llvm-g++-4.2
lrwxr-xr-x     1 root   wheel        32 Jul 31 12:17 llvm-g++-4.2 -> ../llvm-gcc-4.2/bin/llvm-g++-4.2
lrwxr-xr-x     1 root   wheel        32 Jul 31 12:17 llvm-gcc -> ../llvm-gcc-4.2/bin/llvm-gcc-4.2
lrwxr-xr-x     1 root   wheel        32 Jul 31 12:17 llvm-gcc-4.2 -> ../llvm-gcc-4.2/bin/llvm-gcc-4.2

When I run: which gcc-4.8 I get /usr/local/bin/gcc-4.8.

Steps to get this done would be very helpful.

Please and thank you.

Best Answer

Assuming you're using bash (it's the default), then you can add /usr/local/bin as your top priority in PATH like this:

echo "PATH=\"/usr/local/bin:$PATH\"" >> ~/.bash_profile

This will ensure that /usr/local/bin is checked before all other areas of your path. Then just start a new terminal session to load the new variable.

Another way to do this:

  cd /usr/bin
  rm cc gcc c++ g++
  ln -s /usr/local/bin/gcc-4.8 cc
  ln -s /usr/local/bin/gcc-4.8 gcc
  ln -s /usr/local/bin/c++-4.8 c++
  ln -s /usr/local/bin/g++-4.8 g++