程序可执行文件无法运行

huangapple go评论102阅读模式
英文:

Program executable does not run

问题

如果我运行 go build -o bin/test ./scripts/test.go,我会得到一个可执行文件,但是当我尝试运行它时,我得到以下错误信息:

Failed to execute process './bin/test'. Reason:
exec: Exec format error
The file './bin/test' is marked as an executable but could not be run by the operating system.

scripts/test.go

package scripts

import (
	"fmt"
)

func main() {
	fmt.Println("hello")
}
英文:

If I run go build -o bin/test ./scripts/test.go I get an executable, but when I try to run it I get

Failed to execute process './bin/test'. Reason:
exec: Exec format error
The file './bin/test' is marked as an executable but could not be run by the operating system.

scripts/test.go

package scripts

import (
	"fmt"
)

func main() {
	fmt.Println("hello")
}

答案1

得分: 2

应该是package main

package main
import "fmt"

func main() {
   fmt.Println("hello")
}

https://tour.golang.org/welcome

英文:

Should be package main:

package main
import "fmt"

func main() {
   fmt.Println("hello")
}

https://tour.golang.org/welcome

答案2

得分: 1

go build命令的文档中详细介绍了它的工作原理。

总结:

  • 构建"main"包将输出一个可执行文件
  • 构建非主要包将输出一个对象(并丢弃它)
  • 使用-o进行构建将强制命令不丢弃输出,并将其保存到指定的文件中

所以,你在这里做的基本上是构建一个非主要包,它输出一个对象文件,而不是可执行文件。通常情况下,这会被丢弃,但由于使用了-o选项,你强制将其输出到一个文件中。

要获得一个实际的可执行文件,你只需要将包名更改为main(正如Steven Penny所指出的那样)。

英文:

The documentation for the go build command has the details about how this works.

Summary:

  • Building "main" packages will output an executable file
  • Building a non-main package will output an object (and discard it)
  • Building with -o will force the command to not discard the output, and save it to the specified file

So basically what you're doing here is building a non-main package, which outputs outputs an object file, not an executable. Normally this is discarded, but due to using the -o option you've forced it to output it to a file.

To get an actual executable, you just need to change the package name to main (as noted by Steven Penny)

huangapple
  • 本文由 发表于 2021年5月25日 10:16:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/67680902.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定