确保GOROOT(Go安装目录)、GOPATH(工作目录)和PATH(可执行文件路径)设置无误。
echo $GOROOT、echo $GOPATH、echo $PATH。~/.bashrc或~/.zshrc中添加(以默认安装路径为例):export GOROOT=/usr/local/go
export GOPATH=$HOME/go
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
source ~/.bashrc(或对应shell配置文件)。go mod init <项目名>创建go.mod文件。go mod tidy自动添加缺失依赖、移除未使用的依赖。go clean -modcache清理模块缓存,再重新下载。go get <包名>@<版本>(如go get github.com/gin-gonic/gin@v1.9.1)指定依赖版本,解决冲突。若编译的目标系统(如CentOS 7)glibc版本低于编译系统(如CentOS 8),会出现GLIBC_xxx not found错误。
docker pull centos:centos7
docker run -v $(pwd):/usr/src/myapp -w /usr/src/myapp centos:centos7 bash -c "yum install -y wget gcc && wget https://mirrors.ustc.edu.cn/golang/go1.20.5.linux-amd64.tar.gz && tar xzf go1.20.5.linux-amd64.tar.gz && rm -rf go1.20.5.linux-amd64.tar.gz && export PATH=/usr/local/go/bin:\$PATH && cd /usr/src/myapp && go build -o myapp"
CGO_ENABLED=0 go build -o myapp。undefined: xxx、syntax error: unexpected comma),定位并修复代码中的语法或逻辑错误。import cycle错误,重构代码消除循环导入(如将公共逻辑提取到新包,或使用接口解耦)。chmod +x myapp添加执行权限。Golang会缓存编译结果,缓存异常可能导致编译失败。运行以下命令清理缓存:
go clean -cache -modcache -i -r
清理后重新编译:go build。
go version。go.mod文件中指定了Go版本(如go 1.20),需确保本地安装的版本与之匹配。sudo yum remove golang),从官网下载最新版本安装。GOOS(目标操作系统)和GOARCH(目标架构):# 编译Linux可执行文件(适用于CentOS)
GOOS=linux GOARCH=amd64 go build -o myapp
# 编译Windows可执行文件
GOOS=windows GOARCH=amd64 go build -o myapp.exe
CGO_ENABLED=0),生成静态链接的可执行文件。libcurl、openssl等库,使用yum安装对应开发包:sudo yum install libcurl-devel openssl-devel gcc gcc-c++
g++ not found等,安装对应编译器:sudo yum install gcc-c++。yum install golang报错,添加Go官方源后再安装:sudo rpm --import https://mirror.go-repo.io/centos/RPM-GPG-KEY-GO-REPO
curl -s https://mirror.go-repo.io/centos/go-repo.repo | sudo tee /etc/yum.repos.d/go-repo.repo
sudo yum install golang