Reputation: 243
My go application directory structure is like this:
/app
go.mod
go.sum
main.go
When I build the app I usually cd into that directory and build.
cd app
go build
I wonder if I can build without cd in to app directory.
When I go go build /app
, it prints go: go.mod file not found in current directory or any parent directory; see 'go help modules'
.
Upvotes: 5
Views: 12377
Reputation: 500
Go now can change directory before build with the help of flag -C
:
go build -C app
"The go subcommands now accept -C to change directory to before performing the command" Source: https://tip.golang.org/doc/go1.20
(You don't need to run cd ..
after this command. Shell stays in the same directory)
Upvotes: 17
Reputation: 52141
See https://golang.org/ref/mod#commands-outside :
go build
needs to be run from a module directory.
The simplest way is to cd
into your module directory (cd /app
) to run your go build
command.
(there probably is some way to create a phony local go.mod
file, and reference your /app
module from there, but I wasn't able to devise a hack to do this)
Upvotes: 3
Reputation: 60
I'm pretty sure to build you will need to be in the app directory.
As a workaround if you are just wanting to be on the command line in a different directory and want to run the build with one command you can just chain the cd and go build commands together like this:
cd app; go build ; cd ..
This is the same amount of typing but could be in your command history just a couple presses of the up arrow away.
Note this is for bash or similar UNIX style shell. If using Windows cmd then I think it would be something like this (Not tested as I don’t have readily available access to a Windows machine right now):
cd app & go build & cd ..
Upvotes: -1