Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Makefile environment variable for specific target

Tags:

makefile

go

I'm working on a go project which has a Makefile like below. Note that the "release" target sets two environment variables so that the "build" target cross-compiles for a specific architecture (which is possibly not that of the build system).

# Generates a container release artifact.
release: export GOOS=linux
release: export GOARCH=amd64
release: build
  docker build ...

# Generates an executable for local use.
build: test
  go build ...

test: fmt vet
  go test ./...

...

The problems is that the GOOS and GOARCH env vars are also detected by the "go test" command which causes that step to fail since cross-platform testing apparently is not supported.

To put it another way, it's like I want to clear the env vars for the "test" target, but the example below doesn't appear to unset the vars as expected:

unexport GOOS
unexport GOARCH
test: fmt vet
    go test ./...

I could remove the "test" dependency for the "build" target and it works fine but that seems like the wrong approach since I wouldn't want to build or release the binary if the tests fail.

Can I somehow modify the Makefile so that the GOOS and GOARCH environment variables are set by the "release" target and used by the "build" target but not the dependent "test" target?

Is there perhaps some other way to cross compile for release and still run the tests as a dependency without otherwise complicating things (such as building via Docker, etc)? Note that the make targets are a bit more complicated than the example above due to several flags for the release and build targets.

like image 528
maerics Avatar asked Sep 14 '26 22:09

maerics


1 Answers

I would do it this way:

test: export GOOS=
test: export GOARCH=
test: fmt vet
    go test ./...
like image 115
Beta Avatar answered Sep 18 '26 03:09

Beta



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!