July 7th 2014

As a newcomer to Go I was recently stumped at how to compile multiple files belonging to the same package. To most people who've used Go for a while this is probably the most trivial of problems, but to a newcomer it takes a little effort to grok how Go goes about this.

Imagine a simple example where you have two files belonging to the same package, myproject/file1.go and myproject/file2.go with file2.go using some function from file1.go.

The most important part to grok is that if both files both start with package myproject then there is no need to import file1.go in file2.go. If you have a function called f in file1.go, then you can use it in file2.go by calling f() without any prefixes. You can then build your project by changing directory to the package directory and running go run or go build.

The confusing part for me was the case where I wanted a main function too. Originally I had a main function in file2.go, but Go requires any file with a main function to have the package name main which means I could no longer use functions from file1.go in file2.go. A good way to solved this is by making a new file myproject/main/file3.go containing the main function and importing the myproject package to use functions from file1.go and file2.go.

To import the myproject package, you have to import the path relative to the environment variable GOPATH. To check what your current GOPATH is, type echo $GOPATH in a terminal window. Some people prefer having all their go code in one central directory containing the different packages in which case How to write Go code is a great guide for directory structure. However in my case I currently have projects in a few separate directories for various reasons in which case I don't have a canonical GOPATH. Instead I add my current project to the GOPATH by typing export GOPATH=$GOPATH:/full/path/to/parent/dir/of/myproject. You can also add this line to your .bashrc to make it permanent.

To import myproject into myproject/main/file3.go you import the path from your updated GOPATH to your project. If the parent directory of your project is in the GOPATH then you can just type import "myproject", but if you follow How to write Go code then it is probably import "github.com/your_user/myproject". Now you can use any function f```` fromfile1.goandfile2.goinfile3.goby usingmyproject.f()``` in your code.

None of the above is rocket science. It's just a particular way of doing things that takes a bit to get used to if you aren't familiar with this way of doing things.