美文网首页
go build 注意事项和坑 2020-07-15

go build 注意事项和坑 2020-07-15

作者: 9_SooHyun | 来源:发表于2020-07-15 10:43 被阅读0次

If the arguments to build are a list of .go files from a single directory,
build treats them as a list of source files specifying a single package.

When compiling packages, build ignores files that end in '_test.go'.

When compiling a single main package, build writes
the resulting executable to an output file named after
the first source file ('go build ed.go rx.go' writes 'ed' or 'ed.exe')
or the source code directory ('go build unix/sam' writes 'sam' or 'sam.exe').
The '.exe' suffix is added when writing a Windows executable.

When compiling multiple packages【编译多个package】 or a single non-main package【编译一个非main的package,即源码中不是package main, 而是package other】,
build compiles the packages but discards the resulting object,
serving only as a check that the packages can be built.【仅仅检查是否能编译,但不保存编译结果】

The -o flag forces build to write the resulting executable or object
to the named output file or directory, instead of the default behavior described
in the last two paragraphs. If the named output is a directory that exists,
then any resulting executables will be written to that directory.【-o outputpath 强制保存编译结果】

来自go help build

关于go build 生成的executable file的路径问题

测试环境:
GOPATH=D:\go\workspace
GOROOT=D:\go
Path=$Path;D:\go\bin

1 跳过文件夹直接build里面的.go文件,失败

C:\Users\user_test>go build main.go
can't load package: package main.go: cannot find package "main.go" in any of:
D:\go\src\main.go (from $GOROOT)
D:\go\workspace\src\main.go (from $GOPATH)

2 不跳过文件夹,build里面的.go文件,失败。但不能在D:\go\workspace\src\main\main.go找到"main/main.go"???只能说明,命令认为"main/main.go"是一个package,但实际上不是,因此出错

C:\Users\user_test>go build main\main.go
can't load package: package main/main.go: cannot find package "main/main.go" in any of:
D:\go\src\main\main.go (from $GOROOT)
D:\go\workspace\src\main\main.go (from $GOPATH)

3 build文件夹,成功。在build的运行目录C:\Users\user_test生成main.exe

C:\Users\user_test>go build main

总结:
从错误提示看,can't load package,说明非同级目录的情况下,go build 只能build package,也就是只能build 一个文件夹,并在build命令的执行目录下,生成以文件夹命名的二进制文件。那么,如果我们进入到与.go文件同级的目录,应该就可以build .go文件了

4. build .go文件必须要进入同级目录(成功),生成.go文件同名的二进制文件

D:\go\workspace\src\main>go build main.go

相关文章

网友评论

      本文标题:go build 注意事项和坑 2020-07-15

      本文链接:https://www.haomeiwen.com/subject/kfldhktx.html