Mac-GO-Build-Windows.exe

Mac-GO-Build-Windows.exe

彼方 18 2024-06-05

1. 问题与原因

Go项目中引用了Sqlite,使用Mac打包时出现以下报错:
2024-06-05-zcldwdui.png
GO环境配置如下:

GO111MODULE="on"
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/edy/Library/Caches/go-build"
GOENV="/Users/edy/Library/Application Support/go/env"
GOEXE=".exe"
GOEXPERIMENT=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOINSECURE=""
GOMODCACHE="/Users/edy/Documents/go_project/pkg/mod"
GONOPROXY=""
GONOSUMDB=""
GOOS="windows"
GOPATH="/Users/edy/Documents/go_project"
GOPRIVATE=""
GOPROXY="https://goproxy.cn,direct"
GOROOT="/usr/local/Cellar/go/1.20.7/libexec"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/Cellar/go/1.20.7/libexec/pkg/tool/darwin_amd64"
GOVCS=""
GOVERSION="go1.20.7"
GCCGO="gccgo"
GOAMD64="v1"
AR="ar"
CC="cc"
CXX="c++"
CGO_ENABLED="1"    // 注意这项配置
GOMOD="/dev/null"
GOWORK=""
CGO_CFLAGS="-O2 -g"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-O2 -g"
CGO_FFLAGS="-O2 -g"
CGO_LDFLAGS="-O2 -g"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-m64 -mthreads -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/kz/37vlxbt17rj_1nlv607pnr080000gn/T/go-build2247616696=/tmp/go-build -gno-record-gcc-switches"

原因:Sqlite使用C语言编写,在Go项目中如果引入了此数据库,则需要配置CGO_ENABLED = 1 开启交叉编译

2. 解决方法

由于我的开发机时Mac平台,需要构建为Windows平台可运行的EXE文件,因此还需要额外安装mingw-w64,以下为ChatGPT对它的解释:
2024-06-05-fdsvqwob.png
使用Homebrew一键安装:

brew install mingw-w64

安装完成后,在GoLand中进行如下配置:
2024-06-05-unmejwqe.png

也可使用下面的命令进行编译:

CC=x86_64-w64-mingw32-gcc CXX=x86_64-w64-mingw32-g++ GOOS=windows GOARCH=amd64 go build -o "文件名.exe"

验证文件有效性:

e@MacBook-Pro wechat-api-bridge % file wechat-api-bridge.exe 
wechat-api-bridge.exe: PE32+ executable (console) x86-64, for MS Windows