Macのgcc, g++をHomebrewを使って最新版にする

モチベーション

私はデスクトップはUbuntu、ノートPCはMacを利用しているのですが、
全く同じC++のコードを両者で同じようにコンパイルした際に、MacでだけWarningが出たりします。
Command Line Toolsで入れたMacのコンパイラがよろしくないのが原因っぽいので、最新版に更新してしまいましょう。

やること

1
$ brew install gcc

インストールはこれだけで終わりです。
Homebrew経由で入れたパッケージは/usr/local/Celler/に保存され、/usr/local/bin/にコマンドのエイリアスが自動で貼られます。
/usr/local/bin/からエイリアスを探し当てます

1
2
$ ls /usr/local/bin | grep gcc
$ ls /usr/local/bin | grep g++

上記コマンドで見つかったgcc-8g++-8がお目当てのエイリアスです。
見つかったエイリアスに対してシンボリックリンクを貼ってあげましょう。

1
2
$ ln -s /usr/local/bin/gcc-8 /usr/local/bin/gcc
$ ln -s /usr/local/bin/g++-8 /usr/local/bin/g++

最後に~/.bash_profileの良い感じの場所に以下の記述をして、優先順位高めのパスを通したら終了です。

1
export PATH=$PATH:/usr/local/bin

結果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/local/Cellar/gcc/8.2.0/libexec/gcc/x86_64-apple-darwin16.7.0/8.2.0/lto-wrapper
Target: x86_64-apple-darwin16.7.0
Configured with: ../configure --build=x86_64-apple-darwin16.7.0 --prefix=/usr/local/Cellar/gcc/8.2.0 --libdir=/usr/local/Cellar/gcc/8.2.0/lib/gcc/8 --enable-languages=c,c++,objc,obj-c++,fortran --program-suffix=-8 --with-gmp=/usr/local/opt/gmp --with-mpfr=/usr/local/opt/mpfr --with-mpc=/usr/local/opt/libmpc --with-isl=/usr/local/opt/isl --with-system-zlib --enable-checking=release --with-pkgversion='Homebrew GCC 8.2.0' --with-bugurl=https://github.com/Homebrew/homebrew-core/issues --disable-nls
Thread model: posix
gcc version 8.2.0 (Homebrew GCC 8.2.0)
$ g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/local/Cellar/gcc/8.2.0/libexec/gcc/x86_64-apple-darwin16.7.0/8.2.0/lto-wrapper
Target: x86_64-apple-darwin16.7.0
Configured with: ../configure --build=x86_64-apple-darwin16.7.0 --prefix=/usr/local/Cellar/gcc/8.2.0 --libdir=/usr/local/Cellar/gcc/8.2.0/lib/gcc/8 --enable-languages=c,c++,objc,obj-c++,fortran --program-suffix=-8 --with-gmp=/usr/local/opt/gmp --with-mpfr=/usr/local/opt/mpfr --with-mpc=/usr/local/opt/libmpc --with-isl=/usr/local/opt/isl --with-system-zlib --enable-checking=release --with-pkgversion='Homebrew GCC 8.2.0' --with-bugurl=https://github.com/Homebrew/homebrew-core/issues --disable-nls
Thread model: posix
gcc version 8.2.0 (Homebrew GCC 8.2.0)