Replacing gcc and g++ with GNU version in macOS
After we install Xcode Command Line Tools, we will get gcc and g++ in /Library/Developer/CommandLineTools/usr/bin and the same contents in /usr/bin.
But the problem is that gcc and g++ are same as clang and clang++. Proof can be obtained from the following content.
% gcc --version
Apple clang version 14.0.3 (clang-1403.0.22.14.1)
Target: arm64-apple-darwin22.5.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
% gcc++ --version
Apple clang version 14.0.3 (clang-1403.0.22.14.1)
Target: arm64-apple-darwin22.5.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
How can we replace them with GNU version ?
-
Install the GNU gcc(contains g++)
We can usebrew install gcc-xxx(xxx is the version number of gcc)
After the installation process, we will get thegcc-xxxandg++-xxxin/opt/homebrew/bin -
Create a symbol link for original binary file gcc-xxx and g++-xxx
Because the original filename is long which contains the version number, we want use thegccandg++command directly. So we need to create a symbol links for them.
Refer to the gcc and g++ from the xcode command line tools, we want create two symlinks inusr/bin. However, when we excuteln -s gcc /usr/bin/gcc, we will get the following result.
ln: /usr/bin/gcc: Operation not permitted
Although we use sudo, we still couldn't create a symlink in /usr/bin. In fact, we can use some special operations to avoid this protection mechanism, but thinking about the system safety, we will use other reasonable operations.
The answer is creating symbolic links in /usr/local/bin, it means users's bin not system's bin.
- Adjust the order of
/usr/binand/usr/local/binin PATH environmental variable
Why we need this operation?
Because we want to usegccandg++directly in termial, so we need to solve the duplicate name problem of these commands in/usr/binand/usr/local/bin.
And we know when system finds commands, it follows the order of PATH environment variable, so we ought to put/usr/local/binbefore/usr/binin PATH environment variable. In fact, the default situation is same as that.

浙公网安备 33010602011771号