How to build executable with name other than Golang package

76,667
go build -o <your desired name>

You can specify the executable name using the -o switch with go build. For your example it would look something like: cd $GOPATH/github.com/username/go-foobar && go build -o foobar. However, you're just left with the executable in the package's folder -- you still need to install it somehow.

However, I don't know of any way to specify that for someone using go get github.com/username/go-foobar to install your tool. For instance, see this answer: https://stackoverflow.com/a/33243591/2415176

If you're not worried about people installing your tool with go get, this is the kind of thing you can wrap in a Makefile.

Share:
76,667

Related videos on Youtube

Petr Razumov
Author by

Petr Razumov

Senior Go Developer and Cloud Expert

Updated on July 08, 2022

Comments

  • Petr Razumov
    Petr Razumov almost 2 years

    Is it possible to build (install, go get, etc) an executable with the name foobar if my Golang package name is one of the following:

    • github.com/username/go-foobar
    • github.com/username/foobar-tools

    and has main.go in the package root?

  • E235
    E235 over 3 years
    If you want to do it for a specific file main.go and you want to call it myapp run it like that: go build -o myapp main.go.
  • Arnold Schrijver
    Arnold Schrijver over 3 years
    Maybe a noob question, but isn't this possible to set in code as a default. I have the case where a project has an ./example dir to be installed. I'd like the binary name to be <project-name>-example by default, without having to specify on cmd-line every time. Is the only way to set the package name accordingly?
  • Craig Kelly
    Craig Kelly over 3 years
    I can't think of anything like that @ArnoldSchrijver - of the various special source options like build tags or the upcoming embedding, I don't think anything lets you change build tags from the source code. I suppose you might be able to hack something together with go generate side effects, but that seems like a path fraught with disaster. The easiest would probably just be a script that builds the examples the way you want.