如何在Mac上交叉编译一个Go程序给Ubuntu?

huangapple go评论95阅读模式
英文:

How do I cross-compile a Go program on a Mac for Ubuntu?

问题

你可以使用交叉编译来生成适用于Vagrant环境的二进制文件。在Mac OS上,你可以使用以下命令来进行交叉编译:

GOOS=linux GOARCH=amd64 go build

这将生成一个适用于Ubuntu Linux的二进制文件。然后,你可以将该二进制文件复制到Vagrant环境中,并在那里运行它。

英文:
vagrant@precise64:/vagrant$ sudo ./myprogram 
./myprogram: 1: ./myprogram: Syntax error: "(" unexpected

I found out this happens when I do not generate the binary file from the same OS. I do go build with Mac OS but I need to run this binary from Vagrant that uses Ubuntu Linux. What command should I use instead of go build from Mac so that I can run the binary program in Vagrant environment?

答案1

得分: 9

注意:随着即将到来的Go 1.5(2015年第三季度),这将变得更容易。

参见“Go 1.5中的交叉编译变得更好了”(仍然来自Dave Cheney)。

要成功进行交叉编译,您需要:

  • 目标平台的编译器,如果它们与您的主机平台不同,例如您在darwin/amd64(6g)上,想要为linux/arm(5g)进行编译。
  • 目标平台的标准库,其中包括在构建Go发行版时生成的一些文件。

随着将Go编译器转换为Go的计划在1.5版本中实现,第一个问题现在已经解决了。

package main

import "fmt"
import "runtime"

func main() {
        fmt.Printf("Hello %s/%s\n", runtime.GOOS, runtime.GOARCH)
}

为darwin/386构建

% env GOOS=darwin GOARCH=386 go build hello.go
# 拷贝到darwin主机
$ ./hello
Hello darwin/386

或者为linux/arm构建

% env GOOS=linux GOARCH=arm GOARM=7 go build hello.go
# 拷贝到linux主机
$ ./hello
Hello linux/arm
英文:

Note: with the upcoming Go 1.5 (Q3 2015), this will be easier.

See "Cross compilation just got a whole lot better in Go 1.5"
(still from Dave Cheney)

> For successful cross compilation you would need

> - compilers for the target platform, if they differed from your host platform, ie you’re on darwin/amd64 (6g) and you want to compile for linux/arm (5g).

  • a standard library for the target platform, which included some files generated at the point your Go distribution was built.

> With the plan to translate the Go compiler into Go coming to fruition in the 1.5 release the first issue is now resolved.

package main

import "fmt"
import "runtime"

func main() {
        fmt.Printf("Hello %s/%s\n", runtime.GOOS, runtime.GOARCH)
}

> build for darwin/386

% env GOOS=darwin GOARCH=386 go build hello.go
# scp to darwin host
$ ./hello
Hello darwin/386

> Or build for linux/arm

% env GOOS=linux GOARCH=arm GOARM=7 go build hello.go
# scp to linux host
$ ./hello
Hello linux/arm

答案2

得分: 1

你需要设置一个交叉编译环境(通过自己构建Go编译器)。Dave Cheney的博客上有很好的说明:http://dave.cheney.net/2013/07/09/an-introduction-to-cross-compilation-with-go-1-1

英文:

You need to set up a cross-compilation environment (by building the go compiler yourself). Dave Cheney's blog has good instructions: http://dave.cheney.net/2013/07/09/an-introduction-to-cross-compilation-with-go-1-1

huangapple
  • 本文由 发表于 2014年4月30日 07:49:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/23377271.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定