7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

go言語でクロスコンパイルしてみる

Last updated at Posted at 2015-07-29

クロスコンパイルできるというのは魅力的なのでgolang入門として
LinuxでWindowsのバイナリを作ってみた

結果

  • 割りと簡単にクロスコンパイルはできた。(コードレベルでの依存性とか互換は除く)
  • C言語だとMinGW-w64でクロスコンパイル環境作るのが大変なのに対して、こちらは非常に楽。
  • 実行ファイルサイズがちょっと大きい(約2MB)のは色々静的リンクしてあるかららしい。
  • 最適化オプション( -gcflags '-N -l' )を付けても変わらず。
  • クロスコンパイルのコストと秤にかけるとそれぐらいいいかなという気がする。

FAQ - golang.jp
http://golang.jp/go_faq#Why_is_my_trivial_program_such_a_large_binary

gcツール・チェーン(5l、6l、8l)のリンカは静的リンクを行います。このため、すべてのGoバイナリには、動的型チェック、リフレクション、パニック時のスタックトレース時に必要となる実行時の型情報と一緒に、Goのランタイムが含まれています。
C言語の簡単な「hello, world」プログラムをgccを使いLinux上でコンパイル・静的リンクを行うと約750kBであり、これにはprintfの実装も含まれています。fmt.Printfを使った同様のGo言語のプログラムでは約1.2MBですが、これには高機能なランタイムサポートが含まれています。

インストール

# yum install golang
# yum install golang-pkg-windows-amd64
# go version
go version go1.4.2 linux/amd64

ソースの作成と実行、コンパイル

$ cat hello.go
package main

import "fmt"

func main() {
  fmt.Printf("hello world\n")
}
$ go run hello.go
hello world
$ go build hello.go
$ ./hello
hello world
$ GOOS=windows GOARCH=amd64 go build hello.go
$ ll -h
合計 3.9M
-rwxr-xr-x 1 ymko users 1.9M  7月 30 02:16 hello
-rwxr-xr-x 1 ymko users 2.0M  7月 30 02:17 hello.exe
-rw-r--r-- 1 ymko users   73  7月 30 02:15 hello.go

Windows側で実行

C:\tmp> hello.exe
hello world

参考

はじめての Go 言語 (on Windows) - Qiita
http://qiita.com/spiegel-im-spiegel/items/dca0df389df1470bdbfa
golang でビルド時に最適化をオフにする - tetsuok の旅 blog
http://tetsuok.hatenablog.com/entry/2012/07/01/062325

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?