What's the correct `go build` syntax to build main module in a subdirectory without changing working directory?

Assume I’m in a Bash shell with a working directory of ~/projects/foo (which may contain a go.mod). How would I build a main module at ~/projects/foo/bar (which also contains a go.mod) given that GO111MODULE=on?

The only way which seems to work (but feels wonky) is (cd foo && go build). Using go1.13.3 on Kubuntu.

2 Likes

This is the command you are looking for: go build -o hello ./bar. The compiled program will have the name hello, and it will be stored in the directory you are when invoking the command.

Without the -o hello, the command will try to create a program named bar. It will fail because there is already a directory with that name in the directory from where you invoke the command.

3 Likes

Nice catch. I did however do something else wrong even before that. Since I am invoking go build in the parent directory of the project I want to build, that directory’s go.mod is always considered first. By running go mod edit -replace example.com/me/foo/bar=./bar I then got to the point that I needed to implement your solution, being able to build the project with go build -o bar/bar example.com/me/foo/bar. Also good to know: submodules within a git repository are versioned with tags in the form bar/vX.Y.Z. Found the solution here: https://github.com/golang/go/issues/27056

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.