1、安装GCC
brew install gcc
brew的安装更新等,自行参考网上其他教程。
2、找到上述命令安装的GCC版本
ls -l /usr/local/bin | grep g++
lrwxr-xr-x 1 xxx admin 33 3 30 15:11 g++-11 -> ../Cellar/gcc/11.2.0_3/bin/g++-11
lrwxr-xr-x 1 xxx admin 55 3 30 15:11 x86_64-apple-darwin21-g++-11 -> ../Cellar/gcc/11.2.0_3/bin/x86_64-apple-darwin21-g++-11
GCC、gcc命令、g++命令 之间的关系,自行参考网上教程。
可以看到目前安装的GCC 版本是11
这里参考:https://blog.csdn.net/muyimo/article/details/91991811
3、配置shell使用GCC提供的相关命令,而不往常Clang的命令:
在 ~/.bash_profile 文件添加
alias gcc='gcc-11'
alias cc='gcc-11'
alias g++='g++-11'
alias c++='c++-11'
上述版本号保持与自己安装的版本号一致。
然后执行:source ~/.bash_profile 让配置生效。
本步骤参考:MacOS 切换 Clang 为 GCC_「已注销」的博客-CSDN博客
4、如果macOS 使用的shell 是zsh,那么需要对zsh的环境进行进一步配置才可以不用每次打开一个窗口都需要执行一次 source ~/.bash_profile 。
做法就是将 source ~/.bash_profile 命令写到zsh的配置文件中。
具体参考:Mac 每次都要执行source ~/.bash_profile 后,配置的环境变量才生效_昵称jc的博客-CSDN博客_mac 环境变量每次都需要source
5、在macOS 中,使用GCC代替Clang后,会出现一些原来可以使用Clang编译的源码,用GCC编译就会报错,总体来说,就是GCC对代码的限制和要求不一样:
(5.1)比如报错:没有头文件wchar.h
更新xcode 命令行工具可以解决,
参考:xcode-select: error: command line tools are already installed, use "Software Update" to install - 简书
(5.2)比如报错:
error: 'for_each' was not declared in this scope
这个就是添加库
#include <algorithm>
然后就可以编译通过。但是原来没加这个头的话,Clang也是可以编译的。不知道为啥?或者Clang默认是加了这个头文件?