Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve "package is not in GOROOT" when using `go build`?

Tags:

go

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?

like image 205
Victor Avatar asked Oct 18 '25 15:10

Victor


1 Answers

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
like image 140
mkopriva Avatar answered Oct 21 '25 04:10

mkopriva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!