草庐IT

linux - 如何在Linux上编译跨平台的Go语言项目?

coder 2023-06-21 原文

我正在尝试在 Linux 上设置我的 Go 编译器,它可以为任何其他架构或平台编译项目。我使用的是官方 Ubuntu 14.04 存储库中的默认包,并且我使用的是 64 位系统。此配置允许我仅针对 Linux 和 64 位系统进行编译。至少我想为 32 位 Linux 甚至 32 位 Windows 系统编译。有可能以某种方式做吗?

另外一件事是我想使用两个 Go 绑定(bind): https://github.com/mattn/go-gtkhttps://github.com/mattn/go-webkit

我正在使用 go-webkit 示例代码进行测试:

package main

import (
    "os"
    "github.com/mattn/go-gtk/gtk"
    "github.com/mattn/go-webkit/webkit"
)

const HTML_STRING = `
<doctype html>
<meta charset="utf-8"/>
<style>
div { font-size: 5em }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function() {
    $('#hello1').slideDown('slow', function() {
        $('#hello2').fadeIn()
    })
})
</script>
<div id="hello1" style="display: none">Hello</div>
<div id="hello2" style="display: none">世界</div>
</div>
`

const MAP_EMBED = `
<style> *{ margin : 0; padding : 0; } </style>
<iframe width="100%" height="100%" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.co.jp/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=osaka&amp;aq=&amp;sll=34.885931,-115.180664&amp;sspn=29.912003,39.506836&amp;brcurrent=3,0x6000e86b2acc70d7:0xa399ff48811f596d,0&amp;ie=UTF8&amp;hq=&amp;hnear=%E5%A4%A7%E9%98%AA%E5%BA%9C%E5%A4%A7%E9%98%AA%E5%B8%82&amp;ll=34.693738,135.502165&amp;spn=0.471406,0.617294&amp;z=11&amp;output=embed"></iframe>
`

func main() {
    gtk.Init(nil)
    window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
    window.SetTitle("webkit")
    window.Connect("destroy", gtk.MainQuit)

    vbox := gtk.NewVBox(false, 1)

    entry := gtk.NewEntry()
    entry.SetText("http://golang.org/")
    vbox.PackStart(entry, false, false, 0)

    swin := gtk.NewScrolledWindow(nil, nil)
    swin.SetPolicy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
    swin.SetShadowType(gtk.SHADOW_IN)

    webview := webkit.NewWebView()
    webview.Connect("load-committed", func() {
        entry.SetText(webview.GetUri())
    })
    swin.Add(webview)

    vbox.Add(swin)

    entry.Connect("activate", func() {
        webview.LoadUri(entry.GetText())
    })
    button := gtk.NewButtonWithLabel("load String")
    button.Clicked(func() {
        webview.LoadString("hello Go GTK!", "text/plain", "utf-8", ".")
    })
    vbox.PackStart(button, false, false, 0)

    button = gtk.NewButtonWithLabel("load HTML String")
    button.Clicked(func() {
        webview.LoadHtmlString(HTML_STRING, ".")
    })
    vbox.PackStart(button, false, false, 0)

    button = gtk.NewButtonWithLabel("Google Maps")
    button.Clicked(func() {
        webview.LoadHtmlString(MAP_EMBED, ".")
    })
    vbox.PackStart(button, false, false, 0)

    window.Add(vbox)
    window.SetSizeRequest(600, 600)
    window.ShowAll()

    proxy := os.Getenv("HTTP_PROXY")
    if len(proxy) > 0 {
        soup_uri := webkit.SoupUri(proxy)
        webkit.GetDefaultSession().Set("proxy-uri", soup_uri)
        soup_uri.Free()
    }
    entry.Emit("activate")
    gtk.Main()
}

如果我用它编译它就可以正常工作

go build

如果我尝试用其他设置编译它:

GOOS=windows GOARCH=386 go build
GOARCH=386 go build

我收到这个错误:

webview.go:5:2: no buildable Go source files in /home/yeeapple/Documents/Coding/Go/Source/src/github.com/mattn/go-gtk/gtk

webview.go:6:2: no buildable Go source files in /home/yeeapple/Documents/Coding/Go/Source/src/github.com/mattn/go-webkit/webkit

我看到的另一件事是,在 GOPATH 目录和 pkg 文件夹中只有带有 *.a 文件的“linux_amd64”文件夹。

例如,如果没有额外的导入,我可以为其他系统编译 Go 文件。跨平台编译适用于:

package main

import "fmt"

func main() {
    fmt.Printf("hello, world\n")
}

版本:

$ go version
go version go1.2.1 linux/amd64

$ gccgo --version
gccgo (Ubuntu 4.9-20140406-0ubuntu1) 4.9.0 20140405 (experimental) [trunk revision 209157]
Copyright (C) 2014 Free Software Foundation, Inc.

最佳答案

在 Go 1.2 中,cgo 特性在交叉编译代码时被禁用。这意味着任何包含 import "C" 的源文件都不会被编译,这使得许多包无法使用。因此,当您的简单“hello world”程序编译时,使用 cgo 的等效程序将失败:

package main

/*
#include <stdlib.h>
#include <stdio.h>
*/
import "C"
import "unsafe"

func main() {
        hello := C.CString("Hello world")
        defer C.free(unsafe.Pointer(hello))
        C.puts(hello)
}

在 amd64 Linux 系统上,如果您尝试为 x86 编译,您将遇到构建失败:

$ GOARCH=386 go build hello.go
can't load package: no buildable Go source files in /...

要编译此程序,您还需要设置环境变量CGO_ENABLED=1 以手动启用cgo。这将导致它尝试编译程序,但如果您没有安装 x86 编译器,它仍然会失败。既然你说你正在使用 Ubuntu,你可以通过安装 gcc-multilib 包来做到这一点:

$ sudo apt-get install gcc-multilib

安装后,您应该能够编译程序:

$ GOARCH=386 CGO_ENABLED=1 go build hello.go
$ file hello
hello: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=..., not stripped

虽然 Ubuntu 带有 Windows 交叉编译工具链(在 mingw32 包中),但您在编译 Windows 二进制文件时仍然会遇到问题:

$ GOOS=windows GOARCH=386 CGO_ENABLED=1 go build hello.go 
go build runtime/cgo: cannot use cgo when compiling for a different operating system

此检查不再出现在 GO 1.3 中,因此您可能会在该版本中获得一些运气。

现在拥有可用的交叉编译器工具链只是战斗的一部分:您还需要为可用的目标架构编译的依赖项版本。对于像 WebKit 这样大的东西来说这不是微不足道的,但你可以使用 CFLAGSLDFLAGSPKG_CONFIG_PATH< 将="" go=""> 环境变量。

关于linux - 如何在Linux上编译跨平台的Go语言项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24350698/

有关linux - 如何在Linux上编译跨平台的Go语言项目?的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  3. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  4. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  5. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  6. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  7. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  8. ruby-on-rails - 项目升级后 Pow 不会更改 ruby​​ 版本 - 2

    我在我的Rails项目中使用Pow和powifygem。现在我尝试升级我的ruby​​版本(从1.9.3到2.0.0,我使用RVM)当我切换ruby​​版本、安装所有gem依赖项时,我通过运行railss并访问localhost:3000确保该应用程序正常运行以前,我通过使用pow访问http://my_app.dev来浏览我的应用程序。升级后,由于错误Bundler::RubyVersionMismatch:YourRubyversionis1.9.3,butyourGemfilespecified2.0.0,此url不起作用我尝试过的:重新创建pow应用程序重启pow服务器更新战俘

  9. ruby - 如何在 Lion 上安装 Xcode 4.6,需要用 RVM 升级 ruby - 2

    我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121

  10. ruby-on-rails - 新 Rails 项目 : 'bundle install' can't install rails in gemfile - 2

    我已经像这样安装了一个新的Rails项目:$railsnewsite它执行并到达:bundleinstall但是当它似乎尝试安装依赖项时我得到了这个错误Gem::Ext::BuildError:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcheckingforlibkern/OSAtomic.h...yescreatingMakefilemake"DESTDIR="cleanmake"DESTDIR="

随机推荐