David Alsh
David Alsh

Reputation: 7649

How to I build a go package for the current OS but output it to a specified folder?

When I run go build main.go, the compiler will output a binary for the current OS in that same folder. In this case I would get a main.exe or a main for OSX or Linux.

If I specify an output it will build omit the file extension on Windows machines.

go build -o ./bin/myproject main.go

Because of the lack of a file extension, you're unable to run the outputted binary on Windows without renaming it.

How do I build a go project, specifying the output folder and getting a binary named appropriately for the OS on the other side?

Upvotes: 3

Views: 54

Answers (1)

Javier Segura
Javier Segura

Reputation: 668

You can handle the logic of the .exe extension in a script. Something like:

#!/usr/bin/env bash

output="./bin/myproject"


if [ -n "$GOOS" ] && [ "$GOOS" = "windows" ]; then
    output+='.exe'
fi

go build -o $output main.go

If you call it build.sh. You can invoke it:

bash build.sh # for using the `GOOS` defined in your environment
GOOS=windows bash build.sh # for building windows binaries (with `.exe` extension)

Upvotes: 2

Related Questions