---
title: "交叉编译Go"
author: "vyloy"
date: "2014-07-23T17:57:32Z"
tags: []
categories: ["编程语言"]
slug: "go"
draft: false
lastmod: "2017-07-22T21:59:52Z"
id: 2095656
url: "https://vyloy.iteye.com/blog/2095656"
---

> 
> Thanks to kind and patient help from golang-nuts, recipe is following:
> 
> 1) One needs to compile Go compiler for different target platforms and architectures. This is done from src folder in go installation. In my case go installation is located in /usr/local/go thus to compile a compiler you need to issue make utility. Before doing this you need to know some caveats.
> 
> There is an issue about CGO library when cross compiling so it is needed to disable CGO library.
> 
> Compiling is done by changing location to source dir, since compiling has to be done in that folder
> 
> cd /usr/local/go/src
> then compile Go compiler:
> 
> sudo GOOS=windows GOARCH=386 CGO_ENABLED=0 ./make.bash --no-clean
> You need to repeat this step for each OS and Architecture you wish to cross compile by changing GOOS and GOARCH parameters.
> 
> If you are working in user mode as I do, sudo is needed because go compiler is in the system dir, otherwise you need to be logged in as super user. On Mac you may need to enable/configure SU access (it is not available by default), but if you have managed to install go you possibly already have root access.
> 
> 2) Once you have all cross compilers built, you can happily cross compile your application by using settings for example:
> 
> GOOS=windows GOARCH=386 go build -o appname.exe appname.go
> 
> GOOS=linux GOARCH=386 CGO_ENABLED=0 go build -o appname.linux appname.go
> Change GOOS and GOARCH to targets you wish to build.
> 
> If you encounter problem with CGO include CGO_ENABLED=0 in the command line, also note that binaries for linux and mac have no extension so you may add extension for the sake of having different files. -o switch instructs go to make output file similar to old compilers for c/c++ thus above used appname.linux can be any other extension.
> 



set GOARCH=amd64
set GOOS=linux
go tool dist install -v pkg/runtime
go install -v -a std


> 
> It tells you it needs all tools built before you can use them.
> 
> If your windows GOARCH is amd64, then you could "build" all required tools by running this small batch programs:
> 
> set GOARCH=amd64
> set GOOS=linux
> go tool dist install -v pkg/runtime
> go install -v -a std
> If that succeeds then you should be able to do what you've described (just use amd64, not AMD64 - it is case sensitive).
> 
> If your windows GOARCH is 386, then you would need to build your 386 tools first. You would need to download mingw gcc for that. Do what user2714852 said.
> 
> Here https://code.google.com/p/go-wiki/wiki/WindowsCrossCompiling are similar instructions for linux, perhaps you find them helpful.
> 
> Alex
> 



<span style="color:white">作者：翁志艺</span>