Reputation: 71
I have the following simple project architecture:
LICENSE Makefile README.md cmd docs
with a test/main.go
inside of the cmd
directory (since I want to build a CLI tool).
My Makefile contains:
test:
gofmt -s -w cmd/test/
go build cmd/test/ -o test
The first command gofmt
works properly but go build
causes an error
package cmd/test is not in GOROOT
What's the correct way to compile?
Upvotes: 4
Views: 31179
Reputation: 1
By prepending the filename with './', you are explicitly supplying a path to the file,. being the current directory (and, by the way, .. is the parent directory).
It does not matter much for writing the file since the default directory for writing is the current directory, but if the file were being executed, it would be significant, because the current directory is typically not on the PATH.
Upvotes: -1
Reputation: 38343
You should be able to make it work with:
go build -o ./test ./cmd/test/*.go
This is because the go build
command takes as its [packages]
argument a list of import paths, or a list of .go files.
go build [-o output] [build flags] [packages]
Build compiles the
packages
named by the import paths, along with their dependencies, but it does not install the results.If the arguments to build are a list of .go files from a single directory, build treats them as a list of source files specifying a single package.
...
Your argument cmd/test/
is neither an import path, nor a list of .go files.
If you want to build a package from its directory's contents you can use ./cmd/test/*.go
and your shell will generally replace that with the list of .go file entries in that directory.
Note however that the recommended approach is to utilize go modules. Wiht go modules you can build your package by specifying its import path instead of the directory's contents. For example given a project structure like the following:
program
└── cmd
└── test
└── test.go
you'd go mod init
from within the root of the project:
go mod init program
that will create a new go.mod
file for your project:
program
├── cmd
│ └── test
│ └── test.go
└── go.mod
and then you can build your package using its import path (which is rooted in the module's path), like so for example:
go build -o ./test program/cmd/test
Upvotes: 9