如何编译包含多个文件的 Go 程序?

我有一个包含三个文件的小程序,它们都属于同一个包(main)。但是当我做 go build main.go的时候,构建不会成功。当它只是一个文件(main.go)时,一切工作正常。

现在我花了一些精力来分离代码,看起来编译器无法找到从 main.go中提取出来的内容并放入这两个其他文件(与 main.go 位于同一目录中)。这会导致 undefined 'type'错误。

如何编译这个由多个文件组成的程序?

201982 次浏览

当您将代码从 main.go分离到例如 more.go中时,您只需将该文件也传递给 go build/go run/go install

所以如果你之前运行

go build main.go

你现在只是

go build main.go more.go

作为进一步信息:

go build --help

国家:

如果参数是. go 文件的列表, Build 将它们视为指定单个包的源文件列表。


请注意,go buildgo installgo run的不同之处在于,前两个状态期望 包裹名称作为参数,而后者期望 查查文件。但是,前两个也将接受去文件,因为去安装。

如果你想知道: build 将只是 build的包/文件,install将产生对象和二进制文件在您的 GOPATH,和 run将编译和运行您的程序。

You could also just run

go build

in your project folder myproject/go/src/myprog

然后你就可以打字了

./myprog

运行你的应用程序

这取决于你的项目结构,但最直接的是:

go build -o ./myproject ./...

然后运行 ./myproject

假设您的项目结构如下所示

- hello
|- main.go

然后转到项目目录并运行

go build -o ./myproject

然后在 shell 上运行 ./myproject

或者

# most easiest; builds and run simultaneously
go run main.go

假设您的主文件嵌套在像 cmd这样的子目录中

- hello
|- cmd
|- main.go

那你就跑吧

go run cmd/main.go

You can use

go build *.go
go run *.go

both will work also you may use

go build .
go run .

Yup! That's very straight forward and that's where the package strategy comes into play. there are three ways to my knowledge. 文件夹结构:

GOPATH/src/
github.com/
abc/
myproject/
adapter/
main.go
pkg1
pkg2

警告: 适配器只能包含包主目录和 sun 目录

  1. 导航到“适配器”文件夹。运行:
    go build main.go
  1. 导航到“适配器”文件夹。运行:
    go build main.go
  1. 导航到 GOPATH/src 识别到包主程序的相对路径,这里是“ myproject/Adapter”。运行:
    go build myproject/adapter

将在您当前所在的目录中创建 exe 文件。

由于 Go 1.11 + ,GOPATH 不再被推荐,新的方法是使用 Go 模块。

假设你正在编写一个名为 simple的程序:

  1. 创建一个目录:

    mkdir simple
    cd simple
    
  2. Create a new module:

    go mod init github.com/username/simple
    # Here, the module name is: github.com/username/simple.
    # You're free to choose any module name.
    # It doesn't matter as long as it's unique.
    # It's better to be a URL: so it can be go-gettable.
    
  3. Put all your files in that directory.

  4. Finally, run:

    go run .
    
  5. Alternatively, you can create an executable program by building it:

    go build .
    
    
    # then:
    ./simple     # if you're on xnix
    
    
    # or, just:
    simple       # if you're on Windows
    

For more information, you may read this.

Go has included support for versioned modules as proposed here since 1.11. The initial prototype vgo was announced in February 2018. In July 2018, versioned modules landed in the main Go repository. In Go 1.14, module support is considered ready for production use, and all users are encouraged to migrate to modules from other dependency management systems.