Go build
最后修改时间 2024 年 4 月 11 日
在本文中,我们将介绍如何使用 Golang 中的 go build 工具构建可执行文件。
Golang 附带 go 工具,用于管理 Go 源代码。它有 doc、build、test 和 run 等多个命令。
go build 命令会编译通过导入路径命名的包及其依赖项,生成一个可执行文件。它不会安装可执行文件。
usage: go build [-o output] [build flags] [packages]
这是命令的语法。
Go build 示例
接下来,我们将构建一个简单的 Go 代码示例。
$ mkdir simple $ cd simple
我们创建并进入项目目录。
$ go mod init com.zetcode/simple
我们使用 go mod init 命令创建一个新模块。它会生成一个 go.mod 文件。
main.go
package main
import (
"fmt"
"runtime"
)
func main() {
go_ver := runtime.Version()
os_ver := runtime.GOOS
arch := runtime.GOARCH
fmt.Println(go_ver)
fmt.Println(os_ver)
fmt.Println(arch)
}
该程序将打印 Go 版本、操作系统名称和架构。
$ go run main.go go run main.go go1.22.2 amd64 linux
go run 命令会编译并运行 Go 程序,但不会构建任何可执行文件。
$ go build $ ls go.mod main.go simple
可执行文件是通过 go build 命令构建的。
$ ./simple go1.22.2 amd64 linux
我们运行二进制文件。
$ file simple simple: ELF 64-bit LSB executable, x86-64, version 1 (SYSV) ...
我们使用 file 工具检查该程序。
$ go build -o bin/simple $ tree . ├── bin │ └── simple ├── go.mod ├── main.go └── simple
使用 -o 选项,我们可以将二进制文件输出到指定目录。
go.mod
module com.zetcode/first go 1.22.2
要更改默认可执行文件名,我们可以更新模块名称的最后一部分。
$ go build $ ./first go1.22.2 amd64 linux
我们以另一个名称构建并运行程序。
构建过程包含两个步骤:编译和链接。我们使用 go tool 命令展示这两个步骤。
$ go tool compile main.go
我们编译程序。会生成一个 main.o 文件。
$ file main.o main.o: current ar archive $ ar t main.o __.PKGDEF _go_.o
这是一个中间存档文件。
$ go tool link -o simple main.o
使用 go tool link,我们生成最终的可执行文件。
接下来,我们在 Windows 上构建程序。过程非常相似。
$ mkdir simple $ cd simple $ go mod init com.zetcode/simple go: creating new go.mod: module com.zetcode/simple
我们创建一个项目目录,然后创建一个 Go 模块。我们使用相同的 main.go 源文件。
$ go build $ ls go.mod main.go simple.exe
我们构建程序。在 Windows 上,可执行文件带有 .exe 后缀。
$ simple.exe go1.22.2 windows amd64
我们运行该程序。
$ file simple.exe simple.exe: PE32+ executable (console) x86-64, for MS Windows
我们使用 file 命令检查该程序。
来源
在本文中,我们使用了 go build 命令。