1. 现象

在 Windows 下编译运行 go 程序时,发现能编译却无法运行。具体说来:

  • 在 Jetbrains Goland 的 build、test、bench 会运行失败,报错This version of %1 is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher.
  • 在控制台运行 go test 或 go test -bench 会运行失败,报错This version of %1 is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher.
  • 在控制台运行 build 能成功,但编译结果(比如叫 XXX.exe)执行的时候会弹窗,标题栏「cmd.exe - 计算机类型不匹配」,内容「映像文件 XXX.exe 无效,但它对另一种计算机类型有效。」。

2. 无效的解决方案

  • 重启 Windows 无法解决问题。
  • 重装 Jetbrains Goland 无法解决问题。
  • 重装 go 无法解决问题。
  • 安装最新版本的 go 无法解决问题。

3. 原因

可能是执行了go env命令,将 Go 环境变量GOARCH的值设置成了arm64

这会导致所有用 go 编译出来的程序——包括命令行和Goland IDE,包括 build、test、bench——生成的 exe 都是 ARM64 架构的,而无法被 X86-64 的机器运行。

判断是否是这个原因,有两种方法:

  • 方法1:如果已经有无法执行的 XXX.exe 文件,直接执行go version -m XXX.exe并检查最后几行。如果有build GOARCH=arm64,则说明是上述原因。
  • 方法2:直接执行go env GOARCH。如果显示arm64,则说明是上述原因。

4. 解决方案

直接在命令行执行go env -w GOARCH=amd64即可。执行完后,可以用go env GOARCH查看效果。

5. 注意

  • arm64amd64看起来很像。amd64才是 X86-64 机器上用的。绝大多数情况下,都应该用amd64作为GOARCH的值。
  • 执行go env -w GOARCH=amd64后,环境变量的变化会永久生效,重启 Windows、重装 Go 也不会失效。
  • GOARCH这些 Go 特有的环境变量,在 Windows 下是看不到的。比如,无法用echo %GOARCH%打印,也不能用系统属性→环境变量查看。