go build 命令用于启动编译,它可以将go语言程序编译成一个可执行文件,只编译不执行
例: 将main.go 和 lib.go 放在gobuild 文件夹下 使用go build 编译
[root@localhost ~]# mkdir gobuild
[root@localhost ~]# cd gobuild
[root@localhost gobuild]# vim main.go
[root@localhost gobuild]# vim lib.go
[root@localhost ~]# ls gobuild
lib.go main.go
[root@localhost ~]# cd gobuild
[root@localhost gobuild]# go build main.go lib.go
[root@localhost gobuild]# ls
lib.go main main.go
[root@localhost gobuild]# ./main
call pkgFunc......
hello world!
指定可执行文件名称 加 -o选项
[root@localhost gobuild]# rm main
rm: remove regular file 'main'? y
[root@localhost gobuild]# ls
lib.go main.go
[root@localhost gobuild]# go build -o myexec main.go lib.go
[root@localhost gobuild]# ls
lib.go main.go myexec
[root@localhost gobuild]# ./myexec
call pkgFunc......
hello world!
go run 命令是将编译和执行合二为一
go run filename.go
[root@localhost ~]# vim hello.go
[root@localhost ~]# go run hello.go
hello world!
编译后的文件在临时目录下
[root@localhost ~]# vim hello.go
[root@localhost ~]# go run hello.go
args: [/tmp/go-build1101835321/b001/exe/hello]
go install 命令是编译并安装源文件,把编译后的文件安装到指定的目录中
要将GOBIN设置安装路径
[root@localhost ~]# sudo vim ~/.bashrc
[root@localhost ~]# source ~/.bashrc
[root@localhost ~]# go env
GO111MODULE=""
GOARCH="amd64"
GOBIN="/usr/local/bin"
GOCACHE="/root/.cache/go-build"
.......
[root@localhost ~]# export GO111MODULE="off"
权限不够 增加权限
[root@localhost ~]# sudo chmod 0777 /usr/local/bin
用 go install 命令编译并安装可执行文件
[root@localhost ~]# go install -x test1.go
WORK=/tmp/go-build881465446
mkdir -p $WORK/b001/
cat >$WORK/b001/importcfg << 'EOF' # internal
# import config
packagefile fmt=/usr/local/go/pkg/linux_amd64/fmt.a
........
mkdir -p /usr/local/bin/
mv $WORK/b001/exe/a.out /usr/local/bin/test1
rm -r $WORK/b001/
安装完毕直接 test1 执行该程序
( go build 需要./test1 是因为没安装go install 已安装则不需要)
[root@localhost ~]# test1
hello world