Cross compile Go on OSX?

前端 未结 6 1678
生来不讨喜
生来不讨喜 2020-12-02 03:39

I am trying to cross-compile a go app on OSX to build binaries for windows and linux. I have read everything what I could find on the net. Closest example that I have found

6条回答
  •  无人及你
    2020-12-02 04:08

    for people who need CGO enabled and cross compile from OSX targeting windows

    I needed CGO enabled while compiling for windows from my mac since I had imported the https://github.com/mattn/go-sqlite3 and it needed it. Compiling according to other answers gave me and error:

    /usr/local/go/src/runtime/cgo/gcc_windows_amd64.c:8:10: fatal error: 'windows.h' file not found
    

    If you're like me and you have to compile with CGO. This is what I did:

    1.We're going to cross compile for windows with a CGO dependent library. First we need a cross compiler installed like mingw-w64

    brew install mingw-w64
    

    This will probably install it here /usr/local/opt/mingw-w64/bin/.

    2.Just like other answers we first need to add our windows arch to our go compiler toolchain now. Compiling a compiler needs a compiler (weird sentence) compiling go compiler needs a separate pre-built compiler. We can download a prebuilt binary or build from source in a folder eg: ~/Documents/go now we can improve our Go compiler, according to top answer but this time with CGO_ENABLED=1 and our separate prebuilt compiler GOROOT_BOOTSTRAP(Pooya is my username):

    cd /usr/local/go/src
    sudo GOOS=windows GOARCH=amd64 CGO_ENABLED=1 GOROOT_BOOTSTRAP=/Users/Pooya/Documents/go ./make.bash --no-clean
    sudo GOOS=windows GOARCH=386 CGO_ENABLED=1 GOROOT_BOOTSTRAP=/Users/Pooya/Documents/go ./make.bash --no-clean
    

    3.Now while compiling our Go code use mingw to compile our go file targeting windows with CGO enabled:

    GOOS="windows" GOARCH="386" CGO_ENABLED="1" CC="/usr/local/opt/mingw-w64/bin/i686-w64-mingw32-gcc" go build hello.go
    GOOS="windows" GOARCH="amd64" CGO_ENABLED="1" CC="/usr/local/opt/mingw-w64/bin/x86_64-w64-mingw32-gcc" go build hello.go
    

提交回复
热议问题