在macOS下启用CGO_ENABLED的交叉编译

go 启用CGO_ENABLED遇到报错的解决方案
gcc_libinit_windows.c:7:10: fatal error: 'windows.h' file not found

在macOS下启用CGO_ENABLED的交叉编译

在启用CGO_ENABLED的情况下,尝试使用下面命令进行Windows平台的交叉编译:

$ CGO_ENABLED=1 GOOS=windows GOARCH=386 go build -x -v -ldflags "-s -w"

出现错误如下:

# runtime/cgo
gcc_libinit_windows.c:7:10: fatal error: 'windows.h' file not found

安装mingw-w64

$ brew install mingw-w64
==> Downloading https://homebrew.bintray.com/bottles/isl-0.22.1.big_sur.bottle.tar.gz
==> Downloading from https://d29vzk4ow07wi7.cloudfront.net/15376fb7aff7adec3786e6a31ec9b5cad585fd01ecbd5c4744ef9461b10965ff?response-content-disposition=attachment%3Bfilename%3D%22isl-0.22.1.big_sur.bottle.tar.gz%22&Policy=eyJTdGF0Z
######################################################################## 100.0%
==> Downloading https://homebrew.bintray.com/bottles/mpfr-4.1.0.big_sur.bottle.tar.gz
==> Downloading from https://d29vzk4ow07wi7.cloudfront.net/1e8eb0326f62d3461d420d98af6fc088daca481cae89fd77a75b420d2e76d776?response-content-disposition=attachment%3Bfilename%3D%22mpfr-4.1.0.big_sur.bottle.tar.gz%22&Policy=eyJTdGF0Z
######################################################################## 100.0%
==> Downloading https://homebrew.bintray.com/bottles/libmpc-1.2.1.big_sur.bottle.tar.gz
######################################################################## 100.0%
==> Downloading https://homebrew.bintray.com/bottles/mingw-w64-8.0.0.catalina.bottle.tar.gz
==> Downloading from https://d29vzk4ow07wi7.cloudfront.net/d294bc0e960294bf573b9da364a8d95a06a257aec8f388c16e2b975ed8e4410c?response-content-disposition=attachment%3Bfilename%3D%22mingw-w64-8.0.0.catalina.bottle.tar.gz%22&Policy=eyJ
######################################################################## 100.0%
==> Installing dependencies for mingw-w64: isl, mpfr and libmpc
==> Installing mingw-w64 dependency: isl
==> Pouring isl-0.22.1.big_sur.bottle.tar.gz
🍺  /usr/local/Cellar/isl/0.22.1: 72 files, 4.9MB
==> Installing mingw-w64 dependency: mpfr
==> Pouring mpfr-4.1.0.big_sur.bottle.tar.gz
🍺  /usr/local/Cellar/mpfr/4.1.0: 30 files, 5.2MB
==> Installing mingw-w64 dependency: libmpc
==> Pouring libmpc-1.2.1.big_sur.bottle.tar.gz
🍺  /usr/local/Cellar/libmpc/1.2.1: 13 files, 425.0KB
==> Installing mingw-w64
==> Pouring mingw-w64-8.0.0.catalina.bottle.tar.gz
🍺  /usr/local/Cellar/mingw-w64/8.0.0: 7,402 files, 854.6MB
$ which x86_64-w64-mingw32-gcc
/usr/local/bin/x86_64-w64-mingw32-gcc

编译x64

可执行文件

$ CGO_ENABLED=1 CC=x86_64-w64-mingw32-gcc CXX=x86_64-w64-mingw32-g++ GOOS=windows GOARCH=amd64 go build -x -v -ldflags "-s -w" -o app.exe

静态库

$ CGO_ENABLED=1 CC=x86_64-w64-mingw32-gcc CXX=x86_64-w64-mingw32-g++ GOOS=windows GOARCH=amd64 go build -buildmode=c-archive -x -v -ldflags "-s -w" -o bin app.go

动态库

-buildmode=c-archive改为-buildmode=c-shared即可

转载资料 出处:https://www.dllhook.com/post/244.html