如何确定程序是在 Go 中构建为 32 位还是 64 位?

How do I determine whether the program was built as 32 bit or 64 bit in Go?

我能得到的最接近的是 runtime.GOARCH,但也可能是 arm,可以是 32 位或 64 位。


我只关心这个程序是如何构建的,而不关心 OS 是否也支持 64 位可执行文件。例如对于 AArch64 CPU 上的 ARM 模式或 x86-64 CPU 上的 32 位兼容模式,我仍然想要 32,因为这是该程序 运行 中的模式。

相关:Detect OS x86 or x64, when compiled as x86 in GO 是关于检测 OS 支持的内容,例如因为可能 运行 一个不同编译的可执行文件。

将 GOARCH 用于 arm:arm (ARM) 和 arm64 (AArch64),

Optional environment variables

$GOOS and $GOARCH

The name of the target operating system and compilation architecture. These default to the values of $GOHOSTOS and $GOHOSTARCH respectively (described below).

Choices for $GOOS are

$GOOS     $GOARCH
darwin    386
darwin    amd64
darwin    arm
darwin    arm64
dragonfly     amd64
freebsd   386
freebsd   amd64
freebsd   arm
linux     386
linux     amd64
linux     arm
linux     arm64
linux     ppc64
linux     ppc64le
linux     mips64
linux     mips64le
netbsd    386
netbsd    amd64
netbsd    arm
openbsd   386
openbsd   amd64
openbsd   arm
plan9     386
plan9     amd64
solaris   amd64
windows   386
windows   amd64
const is64Bit = uint64(^uintptr(0)) == ^uint64(0)

这是有效的,因为如果 uintptr 是 32 位,^uintptr(0) 将是 0xffffffff 而不是 0xffffffffffffffff

^uint64(0) 将始终是 0xffffffffffffffff,无论是 32 位还是 64 位架构。