How to cross compile from Windows to Linux?

Viewed 92632

I've installed Go 1.2 on a Windows machine, wrote up a dummy program and set the environment variables GOARCH and GOOS to "AMD64" and "linux" respectively.

When i issue the "go build" command, i receive an error:

go build runtime: linux/amd64 must be bootstrapped using make.bat

What does this mean?

6 Answers

To set the PowerShell environment variables use (no admin mode required):
$env:GOOS = "linux"
Than build your programm go build

The changed environment variable is only pesent in the current PowerShell window. Everything will be resetted when you reopen the window.

If you using docker, you can build a docker image for linux builts. For example:

First of all, you can prepare a DockerFile as follows:

FROM golang:1.15-alpine3.12 as builder

RUN mkdir /go/src/hello

WORKDIR /go/src/hello

#install nano, zip and git
RUN apk add nano zip git

COPY ./ ./

#build main
RUN GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o main

#zip main
RUN zip main.zip main

Than you can build an image with docker build -t yourname/hello . After that have to export your zip file from this image:

  • First, use the image as a container with the command docker run -it yourname / hello.
  • Second, open a new terminal and run the docker ps to view the Container IDs.
  • And finally, run the command docker cp YOUR_WORKING_CONTAINER_ID:/go/src/hello/main.zip . to export the zip file.

This can be a long way, but it will allow you to build using docker without being dependent on the platform. Below is an example developed by me for using a docker image for updating golang lambda function (via aws-cli).

To build a program that is written by you, you can build it in a single command.

env GOOS=`target-OS` GOARCH=`target-architecture` go build .

PS: Don't miss out the . (You have to be in the program directory)

Replace target-OS and target-architecture from the list below

GOOS - Target Operating System GOARCH - Target Architecture
android arm
darwin 386
darwin amd64
darwin arm
darwin arm64
dragonfly amd64
freebsd 386
freebsd amd64
freebsd arm
linux 386
linux amd64
linux arm
linux arm64
linux ppc64
linux ppc64le
linux mips
linux mipsle
linux mips64
linux mips64le
netbsd 386
netbsd amd64
netbsd arm
openbsd 386
openbsd amd64
openbsd arm
plan9 386
plan9 amd64
solaris amd64
windows 386
windows amd64

Example: For a windows system with amd64 architecture we would use

env GOOS=windows GOARCH=amd64 go build .

Build from other source code

Related