Go作为跨平台的编程语言,与其他跨平台语言相比,它还多了一个跨平台编译的神奇操作
跨平台编译语法
Windows
SET CGO_ENABLED=0
SET GOOS=os
SET GOARCH=arch
go build
CGO_ENABLED
这个参数默认为1,开启CGO。 需要指定为0来关闭,因为CGO不支持交叉编译。
GOOS
设置系统类型,可选值:linux
,windows
,darwin
,freebsd
GOARCH
设置底层架构,常用选值:arm64
,amd64
Linux&&Mac
export CGO_ENABLED=0
export GOOS=os
export GOARCH=arch
go build
实践
Windows编译
To Linux X86
SET CGO_ENABLED=0
SET GOOS=linux
SET GOARCH=amd64
go build
To Linux Arm64
SET CGO_ENABLED=0
SET GOOS=linux
SET GOARCH=arm64
go build
Linux编译
export CGO_ENABLED=0
export GOOS=linux
export GOARCH=arm64
go build
效果
liumou@liumou-PC:~/LinuxData/git/golang/dmeo$ export CGO_ENABLED=0
liumou@liumou-PC:~/LinuxData/git/golang/dmeo$ export GOOS=os
liumou@liumou-PC:~/LinuxData/git/golang/dmeo$ export GOARCH=arch
liumou@liumou-PC:~/LinuxData/git/golang/dmeo$ export GOOS=linux
liumou@liumou-PC:~/LinuxData/git/golang/dmeo$ export GOARCH=arm64
liumou@liumou-PC:~/LinuxData/git/golang/dmeo$ go build
liumou@liumou-PC:~/LinuxData/git/golang/dmeo$ ./demo
bash: ./demo:无法执行二进制文件: 可执行文件格式错误
liumou@liumou-PC:~/LinuxData/git/golang/dmeo$ export GOARCH=amd64
liumou@liumou-PC:~/LinuxData/git/golang/dmeo$ ./demo
bash: ./demo:无法执行二进制文件: 可执行文件格式错误
liumou@liumou-PC:~/LinuxData/git/golang/dmeo$ go build
liumou@liumou-PC:~/LinuxData/git/golang/dmeo$ ./demo
1
baidu.com:443
2022-11-18 00:25:32 [INFO] [/home/liumou/go/pkg/mod/gitee.com/liumou_site/glbm@v0.0.0-20221116163509-fbfb6fc7fef8/network.go:48] Request succeeded
百度访问成功
2022-11-18 00:25:32 [INFO] [/home/liumou/go/pkg/mod/gitee.com/liumou_site/glbm@v0.0.0-20221116163509-fbfb6fc7fef8/Command.go:67] [ vsftpd ] Uninstall
combined out:
2022/11/18 00:25:34 cmd.Run() failed with exit status 1
liumou@liumou-PC:~/LinuxData/git/golang/dmeo$