How to compile Go program consisting of multiple files?

前端 未结 7 1070
野的像风
野的像风 2020-12-04 09:15

I have a small program that consists of three files, all belonging to the same package (main), but when I do \"go build main.go\" the build doesn\'t succeed. When it was jus

7条回答
  •  没有蜡笔的小新
    2020-12-04 10:10

    Since Go 1.11+, GOPATH is no longer recommended, the new way is using Go Modules.

    Say you're writing a program called simple:

    1. Create a directory:

      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.

提交回复
热议问题