简体   繁体   中英

Golang: How to cross compile on Linux for Windows

如何在 Linux 上交叉编译 Go 项目以生成在 Windows 上运行的可执行文件?

To build from Linux to Windows, you need to set the environment variables GOOS to Windows and GOARCH to amd64 .

On Bash or ZSH:

% GOOS=windows GOARCH=amd64 go build

If your package requires CGO then you need to use the mingw-w64 compiler:

sudo apt-get install gcc-multilib
sudo apt-get install gcc-mingw-w64

GOOS=windows GOARCH=386 \
  CGO_ENABLED=1 CXX=i686-w64-mingw32-g++ CC=i686-w64-mingw32-gcc \
  go build

Introduction

During your production process you may want to build your go program to support a windows architecture, but this is not always easy but here's a guide to help you building your go program for windows

CGO

Cgo is an element of go that allow Go packages to call C code.

But weather you're using CGO or not is not as easy as "did I called C code?" because while you may didn't have called C code in you Go program, a package that you're using probably does.

To figure it out the easiest thing is to try without and if it's not working try the second option. (But you can also try this if you want to)

If you don't need CGO

if you don't need CGO, building your go program to another platform is pretty easy as go natively support cross-platform compiling. all you need to do is this:

x64

#Compile your go program to the windows x64 platform 
env GOOS=windows GOARCH=amd64 go build package-import-path

x32

#Compile your go program to the windows x32 platform 
env GOOS=windows GOARCH=386 go build package-import-path

Tip: Since go natively support cross compiling, you can easely build your program to other platform as well, further reading here

If you need CGO

if you need CGO, building your program will be a little bit more complicated since C doesn't support native cross-platform compiling.. But don't wory! It is still pretty easy using the MinGW64 project.

Requirements

Since we will be using mingw64 to build our project, we'll need to make sure mingw is installed. If it's not here's how you can install it:

Ubuntu

On ubuntu simply run:

sudo apt-get install gcc-mingw-w64

Fedora

On fedora simply run:

sudo dnf install mingw64-gcc

Build

Now that we met the requirements, we can now build our project

For windows x64 architecture

To build your program on a windows x64 architecture run:

GOOS=windows GOARCH=amd64 CGO_ENABLED=1 CXX=x86_64-w64-mingw32-g++ CC=x86_64-w64-mingw32-gcc go build package-import-path

For windows x32 architecture

To build your program on a windows x32 architecture run:

GOOS=windows GOARCH=386 CGO_ENABLED=1 CXX=i686-w64-mingw32-g++ CC=i686-w64-mingw32-gcc go build package-import-path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM