LoginSignup
5
1

More than 3 years have passed since last update.

【Go】CGO有効でwindows/amd64にクロスコンパイルする

Last updated at Posted at 2020-09-16

概要

  • GoのプロジェクトをCIで windows/amd64 にクロスコンパイルするのに苦労した
  • C++のDLLを使わなければならなかったので Cgo を使っている

こうしたら出来た


build:
  image: golang:1.13
  before_script:
...
    - apt -y update
    - apt -y install gcc-multilib
    - apt -y install gcc-mingw-w64
    - apt -y install binutils-mingw-w64
...
  script:
    - GOOS=windows GOARCH=amd64 CGO_ENABLED=1 CXX=x86_64-w64-mingw32-g++ CC=x86_64-w64-mingw32-gcc go build .
...

apt -y install がたくさんあるので本当はDockerイメージ作っておいた方がいいのかな

試したこと

1. Linuxコンテナ上でクロスコンパイル

image: golang:1.13
...
script:
  - GOOS=windows GOARCH=amd64 go build .

こう言われた

build constraints exclude all Go files in /go/src/xxx/

CGOが無効?
https://github.com/golang/go/issues/29074

$ go env
...
CGO_ENABLED="1"
...

いや、 1 になってる。
と思ったら、クロスコンパイルではCGO_ENABLEDが有効にならないらしい
https://blog.hatappi.me/entry/2017/11/23/204211

2. CGOを有効にした

$ GOOS=windows GOARCH=amd64 CGO_ENABLED=1 go build .
$ runtime/cgo
gcc: error: unrecognized command line option '-mthreads'; did you mean '-pthread'?

また怒られた。今度はCコンパイラを指定しないといけないっぽい。
https://github.com/mattn/go-sqlite3/issues/303
どこにでも mattn さんいる。すごい。

3. mingw64を使った

$ sudo apt install gcc-multilib
$ sudo apt install gcc-mingw-w64
$ sudo apt install binutils-mingw-w64
$ GOOS=windows GOARCH=amd64 CGO_ENABLED=1 CXX=x86_64-w64-mingw32-g++ CC=x86_64-w64-mingw32-gcc go build .

できた!

Job succeeded
5
1
1

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
5
1