1

When I build a Go binary, I usually do something like this:

go build -ldflags "-X main.basedir somevar" -o mybuilddir/bin/myfile mypackage/main"

this builds the binary and places it in a custom directory. But this doesn't keep the "intermediate" package files beneath pkg/, which would speed up the next compilation runs.

The solution would be go install, but I cannot specify an output directory. It seems to be possible to set the binary directory with GOBIN, but I am unable to specify the name of the executable (always main).

What is a possible solution to this problem?

  • Custom destionation directory
  • Custom name (not main)
  • Keep intermediate generated package files (.a)

This is the src directory of GOPATH:

GOPATH/src$ tree 
.
└── mypackage
    ├── packagea
    │   └── packagea.go
    ├── packageb
    │   └── packageb.go
    └── main
        └── mypackage.go

With go install, the package files (.a) are created in $GOPATH/pkg, with go build, I can't find the .a files anywhere.

topskip
  • 16,207
  • 15
  • 67
  • 99
  • Did you try to add `GOPATH=mybuilddir/` before the `go build ...`? As in `GOPATH=mybuilddir go build ...` – VonC Nov 18 '14 at 08:45
  • @VonC The `GOPATH` is set and in it's `src` directory there is a directory called `mypackage` and a subdirectory called `main` with the `.go` file to be used as a `main` executable. – topskip Nov 18 '14 at 08:48
  • Ok, where is the `pkg/` created then? Not in `GOPATH/pkg`, I presume? – VonC Nov 18 '14 at 08:50
  • @VonC See my revised question: with `go install`, the `.a` files are inside `GOPATH/pkg`, with `go build`, no `.a` files are created. – topskip Nov 18 '14 at 08:54
  • This seems to help me: http://stackoverflow.com/questions/14284375/can-i-have-a-library-and-binary-with-the-same-name – topskip Nov 18 '14 at 09:02
  • The fact that you don't find .a after a go build seems expected (as I detail in my answer below) – VonC Nov 18 '14 at 09:11

1 Answers1

6

Update Nov. 2017: Go 1.10 (Q1 2018) will add caching for go build and go install: see "go build rebuilds unnecessarily".


Original answer (2014)

With go install, the package files (.a) are created in $GOPATH/pkg, with go build, I can't find the .a files anywhere.

As mentioned in "How does the go build command work ?"

The final step is to pack the object file into an archive file, .a, which the linker and the compiler consume.

Because we invoked go build on a package, the result is discarded as $WORK is deleted after the build completes.
If we invoke go install -x two additional lines appear in the output

mkdir -p /home/dfc/go/pkg/linux_arm/crypto/
cp $WORK/crypto/hmac.a /home/dfc/go/pkg/linux_arm/crypto/hmac.a

This demonstrates the difference between go build and install;

  • build builds,
  • install builds then installs the result to be used by other builds.
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250