Reputation: 24602
I'm writing a Go package, let's call it coolstuff. I want to include an example.go file that runs examples from the coolstuff API. But the default Makefile won't build the coolstuff package and example.go, complaining:
example.go:1: package main; expected coolstuff
example.go:3: can't find import: coolstuff
How can I a) compile the package, b) install the package so that any future code I write will know how to find coolstuff, and c) build example.go, which depends on coolstuff?
Do I need two Makefiles, one for the package and one for example.go?
Upvotes: 0
Views: 342
Reputation: 94689
There are several ways to do that.
1) That's not exactly what you have described, but it is possible to add a file called example_test.go
to your coolstuff package. If you just goinstall your package, this file will be ignored, however when you are executing gotest inside your coolstuff package, then gotest will automatically build your package including all *_test.go
files and run them. That`s in my opinion the easiest way, since you do not have to deal with several packages and you can also provide many independent examples / test cases. Future go versions will be able to add those examples to your godoc pkg documentation.
2) If you feel uncomfortable about using Makefiles, then you might want to take a closer look at goinstall. You can set the GOPATH
environment variable to define your own project directory. An example directory structure which is suitable for goinstall is given at the bottom of the page. ("bar" is similar to your "coolstuff pkg there, and "qux" might be your "example"). goinstall will figure out all those build dependencies automatically for you.
3) Using Makefiles is also possible. Creating two of them, one which is based on Make.pkg for your coolstuff package directory and another one which is based on Make.cmd for your example directory sounds like a good idea. You can find some examples of go Makefiles here.
Upvotes: 3