macOS开发Golang报错:fatal error: ‘CoreFoundation/CoreFoundation.h‘ file not found

之前写go用到gorm连接MySQL时,报如下错:

# runtime/cgo _cgo_export.c:3:10: fatal error: 'stdlib.h' file not found

具体解决办法见我的上一篇文章:解决MacOS系统的Go报错问题:# runtime/cgo _cgo_export.c:3:10: fatal error: ‘stdlib.h‘ file not found
今天又遇到了令人头大的问题:

# github.com/shirou/gopsutil/v3/disk
../../../../go/pkg/mod/github.com/shirou/gopsutil/v3@v3.23.2/disk/disk_darwin_cgo.go:9:10: fatal error: 'CoreFoundation/CoreFoundation.h' file not found
#include <CoreFoundation/CoreFoundation.h>
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.

又是各种搜:chatGPT、GPT4、Google…,各种尝试,又把macOS系统版本从13.2升级到了13.3,Xcode版本从14.2升级到了14.3,卸载了之前CommonTools从Apple官网下载的版本,重新使用命令行安装:

xcode-select --install

但是·····还是没能解决
又在~/.zshrc文件中配置各种环境变量,都失败了
*(
——————————————————————————
注意:如果你用的终端是zsh,那么配置环境变量时就去找 ~/.zshrc ,
如果你用的是bash,就去找~/.bash_profile
常用的2个命令:

open ~/.zshrc // 打开环境变量配置文件
source ~/.zshrc // 更改保存后让其立即生效

——————————————————————————
)*
又看到如下一遍好文(可能有的猿友会通过此方法解决,因此分享一下):
Mac新机器 10.15.6 系统 go debug报错解决方案
通过软链接的形式将CoreFoundation头文件挂载到根目录,便于编译时找打头文件,似乎又看到了希望,进入MacOS恢复模式,禁用了SIP,但是我的电脑在禁用SIP后,执行sudo mount -uw /仍然会遇到权限问题,造成挂载不成功

sudo mount -uw /遇到报错:mount_apfs: volume could not be mounted: Permission denied
mount: / failed with 66

即使通过sudi -i以管理员身份运行终端,还是不行,都失败了。
绝望中又想到,是否可以通过再去配置环境变量(虽然配了,但应该是没配正确),来代替软链接的方式,又问了GPT,这次它的回答多了我重点标注的那句,export SDKROOT=“/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk”,CPATH与CPLUS_INCLUDE_PATH在我之前尝试解决中都配过,但是这句我之前没有配置过,因此就配到了我的环境变量配置里:
macOS开发Golang报错:fatal error: ‘CoreFoundation/CoreFoundation.h‘ file not found_第1张图片
最后我的~/.zshrc配置完是这个样子(只列出了与报错相关的几个):

export C_INCLUDE_PATH="/usr/local/include:/usr/include:/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/:/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk:${C_INCLUDE_PATH}"
export CPATH="/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers:/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Security.framework/Headers:$CPATH"
export CPLUS_INCLUDE_PATH="/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers:/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Security.framework/Headers:/usr/local/include:/usr/include:$CPLUS_INCLUDE_PATH"
export SDKROOT="/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk"

配置完后,对项目重新清空了依赖,又重新安装了一遍:

go clean -modcache
go mod tidy

重新运行,成功了!!
功夫不负有心人,此问题折腾了一天半,终于解决了,又可以愉快的继续写代码了!

你可能感兴趣的:(Golang,macos,golang,xcode,CoreFoundation)