Cross-build with Golang

Teerayut Hiruntaraporn
2 min readDec 17, 2021

--

พอดีมีเหตุให้ต้อง build executable ของ Golang ให้ไปใช้ใน Windows ทั้ง 32bit และ 64bit เลยมาบันทึกไว้

CR: https://www.pngkey.com/maxpic/u2e6t4e6r5u2q8i1/

วิธีการ build executable ปกติ

ท่าที่ง่ายที่สุดก็คือการ build ตาม native platform นั้นๆ โดยพิมพ์คำสั่งว่า

go build

จะได้ executable ตาม native platform ที่ใช้งานอยู่

Cross-Build

Cross Build คือการ สร้าง Executable สำหรับ Platform ที่ไม่ตรงกับ Native Platform ที่ใช้อยู่ เช่น ถ้าเราทำงานอยู่บน Mac แล้วจำเป็นต้องสร้าง Executable เพื่อไปใช้งานใน Windows Environment เป็นต้น

แต่ถ้าจะทำ cross-build ไปยัง architecture อื่นเช่น i386 หรือ arm จำเป็นต้องมีการตั้งค่า Target OS และ Target Architecture เพิ่มเช่น

## กรณี windows 
set GOOS=windows
set GOARCH=386
go build
## กรณี Unix
GOOS=windows GOARCH=386 go build

นอกจากนี้ยังจำเป็นต้องติดตั้ง Compiler ที่สามารถทำการ Cross Build ได้ เช่น

สำหรับการติดตั้งก็ไม่ยากมากครับ

ถ้าเป็น Windows ก็ลง installer ได้เลย

ถ้าเป็น Linux ก็อาจจะใช้ท่ามาตรฐานเช่น

apt-get install gcc-mingw-w64

ปัญหาในส่วนของ Windows ที่อาจจะทำให้ build ไม่ได้

ในกรณีที่ Windows อาจจะมีบางกรณีที่ไม่สามารถที่จะ build cross platform ได้ เพราะ ซึ่งอาจจะด้วย MinGW ไม่ได้ support cross-platform บน Windows อย่างสมบูรณ์ ​ โดยเฉพาะเมื่อมีความจำเป็นต้องใช้ CGO

บางที่จะแนะนำให้ใช้ TDM-GCC-64 แทน

เมื่อต้องการ Build ใน Linux

ในกรณีที่เป็น Linux หรือ การ build ผ่าน docker จุดที่สำหรับหลังจากที่ลงโปรแกรมที่จำเป็นเสร็จเรียบร้อยแล้ว คือการเลือก Target architecture, os และ compiler ให้สอดคล้องกัน เช่น

กรณีที่เป็น Windows 32-bit

GOOS=windows GOARCH=386 CGO_ENABLED=1 CC=i686-w64-mingw32-gcc  go build

หรือในกรณีที่เป็น Windows 64-bit

GOOS=windows GOARCH=amd64 CGO_ENABLED=1 CC=x86_64-w64-mingw32-gcc go build

ถ้ามีการตั้งอะไรไม่สอดคล้องกันก็อาจจะเกิด error ได้เช่น

GOOS=windows GOARCH=amd64 CGO_ENABLED=1 CC=i686-w64-mingw32-gcc  go build 
# runtime/cgo
cc1: sorry, unimplemented: 64-bit mode not compiled in

อ้างอิง

  1. https://github.com/mattn/go-sqlite3/issues/303
  2. https://www.digitalocean.com/community/tutorials/how-to-build-go-executables-for-multiple-platforms-on-ubuntu-16-04

--

--

Teerayut Hiruntaraporn
Teerayut Hiruntaraporn

No responses yet