Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go build multiple/nested packages?

Tags:

go

I just started writing Go today (so 0 experience), and wonder if Go supports any form of "building all source files" like what mvn install does.

My project structure is

src
  `-github.com
          `-myproject
               |- package1
               |     `- main.go
               `- package2
                     |- lib1_used_by_main.go
                     `- lib2_used_by_main.go

When I do

cd src/github.com/myproject
go build

this fails with no buildable Go source files in src/github.com/myproject, which is kind of right, because all source files are in subpackages.

Is there a command to build all subpackages, without listing each of them explicitly?

like image 388
stackoverflower Avatar asked Feb 22 '17 18:02

stackoverflower


People also ask

How do I make multiple packages in Golang?

Check your GOPATH in environment variables and set it to the directory which contains all Go files. Create a new folder with the name of the package you wish to create. In the folder created in step 2, create your go file that holds the Go package code you wish to create.

Can a go package have multiple files?

As Wombologist mentioned, you can split different files under the same package without problem, assuming they share the same package definition.

How do I compile a .go file?

From the command line in the hello directory, run the go build command to compile the code into an executable. From the command line in the hello directory, run the new hello executable to confirm that the code works.

Where does go build put binaries?

This command does perform the exact operation as go build but places the binary in $GOPATH/bin` directory alongside the binaries of third-party tools installed via go get now if you run $GOPATH/bin/hello you will see Hello, world!


1 Answers

After you cd to the base directory, use go build ./... Note that there are 3 periods as it is an ellipsis. This will recursively build all subdirectories. Of course you can always do go build path/to/my/base/... from wherever without needing to cd to the directory.

This is very useful for those who use an IDE that relies on the go/pkg directory, such as SublimeText3 with GoSublime. Making changes to a dependency package won't update the autocompletes until you build the package, which places it in the go/pkg directory.

My own projects are broken into a multiple package structure, so I frequently have to go build ./... to update my autocompletion.

like image 193
RayfenWindspear Avatar answered Oct 06 '22 15:10

RayfenWindspear