To cross compile for Linux, we'll need a GCC or compatible compiler that can build Linux binary files. On macOS, the easiest platform to use is musl-cross (musl has many other advantages that you can read more about at www.etalabs.net/compare_libcs.html). On Windows, the linux-gcc
package will be suitable. Let's work through the steps for each of these.
To install the dependencies for cross compiling for Linux, we'll use the Homebrew package manager again—see the previous sections or https://brew.sh/ for installation instructions. Using Homebrew, we'll install the appropriate packages by opening a Terminal and executing the following commands (the HOMEBREW_BUILD_FROM_SOURCE
variable works around an issue with musl-cross depending on potentially old versions of libraries):
export HOMEBREW_BUILD_FROM_SOURCE=1
brew install FiloSottile/musl-cross/musl-cross
Once the installation is complete (this may take some time as it's building a complete compiler toolchain from source), you should be able to build for Linux. To do so, you'll need to set the environment variables, CC=x86_64-linux-musl-gcc
and CXX=x86_64-linux-musl-g++
.
Using MSYS2 as earlier, we can install the gcc
package to provide cross compilation for Linux:
pacman -S gcc
After the installation has completed, we can tell our Go compiler to use gcc
by setting the environment variable CC=gcc
. Compilation should now succeed following the instructions in your current example, such as the following:
GOOS=linux CGO_ENABLED=1 CC=gcc go build
It's possible, at this point, that you may see additional errors due to missing headers. To fix this, you'll need to search for, and install, the required libraries. If, for example, your error stated that SDL couldn't be found then you would use pacman -Ss sdl
to search for the right package to install. If you can't find an appropriate package, you may need to install Cygwin www.cygwin.com/ (as it has a larger package library) or Windows subsystem for Linux docs.microsoft.com/en-us/windows/wsl/ (as that brings a full Linux distribution to your Windows desktop).