Replacing gcc and g++ with GNU version in macOS

发布时间 2023-09-15 17:33:29作者: 0x7F

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 ?

  1. Install the GNU gcc(contains g++)
    We can use brew install gcc-xxx (xxx is the version number of gcc)
    After the installation process, we will get the gcc-xxx and g++-xxx in /opt/homebrew/bin

  2. 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 the gcc and g++ 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 in usr/bin. However, when we excute ln -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.

  1. Adjust the order of /usr/bin and /usr/local/bin in PATH environmental variable
    Why we need this operation?
    Because we want to use gcc and g++ directly in termial, so we need to solve the duplicate name problem of these commands in /usr/bin and /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/bin before /usr/bin in PATH environment variable. In fact, the default situation is same as that.