Golang在Mac、Linux、Windows下如何交叉编译的实现

ZGCdemo 2020-05-13

Golang æ¯æ交åç¼è¯ï¼å¨ä¸ä¸ªå¹³å°ä¸çæå¦ä¸ä¸ªå¹³å°çå¯æ§è¡ç¨åºï¼æè¿ä½¿ç¨äºä¸ä¸ï¼é常好ç¨ï¼è¿éå¤å¿ä¸ä¸ã

Mac ä¸ç¼è¯ Linux å Windows 64ä½å¯æ§è¡ç¨åº

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build main.go
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go

Linux ä¸ç¼è¯ Mac å Windows 64ä½å¯æ§è¡ç¨åº

CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build main.go
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go

Windows ä¸ç¼è¯ Mac å Linux 64ä½å¯æ§è¡ç¨åº

SET CGO_ENABLED=0
SET GOOS=darwin
SET GOARCH=amd64
go build main.go

SET CGO_ENABLED=0
SET GOOS=linux
SET GOARCH=amd64
go build main.go
  • GOOSï¼ç®æ å¹³å°çæä½ç³»ç»ï¼darwinãfreebsdãlinuxãwindowsï¼
  • GOARCHï¼ç®æ å¹³å°çä½ç³»æ¶æï¼386ãamd64ãarmï¼

交åç¼è¯ä¸æ¯æ CGO æ以è¦ç¦ç¨å®

ä¸é¢çå½ä»¤ç¼è¯ 64 ä½å¯æ§è¡ç¨åºï¼ä½ å½ç¶åºè¯¥ä¹ä¼ä½¿ç¨ 386 ç¼è¯ 32 ä½å¯æ§è¡ç¨åº

å¨ç½ç»ä¸ç诸å¤æç¨ä¸­å¯è½ä¼çå°ä¸é¢çç¼è¯å½ä»¤

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build hello.go

å¶ä¸­CGO_ENABLED=0çæææ¯ä½¿ç¨C语è¨çæ¬çGOç¼è¯å¨ï¼åæ°é置为0çæ¶åå°±å³é­C语è¨çæ¬çç¼è¯å¨äºãèªä»golang1.5以ågo就使ç¨go语è¨ç¼è¯å¨è¿è¡ç¼è¯äºãå¨golang1.9å½ä¸­æ²¡æ使ç¨CGO_ENABLEDåæ°åç°ä¾ç¶å¯ä»¥æ­£å¸¸ç¼è¯ãå½ç¶ä½¿ç¨äºä¹å¯ä»¥æ­£å¸¸ç¼è¯ãæ¯å¦æCGO_ENABLEDåæ°è®¾ç½®æ1ï¼å³å¨ç¼è¯çè¿ç¨å½ä¸­ä½¿ç¨CGOç¼è¯å¨ï¼æåç°ä¾ç¶æ¯å¯ä»¥æ­£å¸¸ç¼è¯çã

å®éä¸å¦æå¨goå½ä¸­ä½¿ç¨äºCçåºï¼æ¯å¦import "C"é»è®¤ä½¿ç¨go buildçæ¶åå°±ä¼å¯å¨CGOç¼è¯å¨ï¼å½ç¶æ们å¯ä»¥ä½¿ç¨CGO_ENABLED=0æ¥æ§å¶go buildæ¯å¦ä½¿ç¨CGOç¼è¯å¨ã

å¾å¤å客é½æå°è¦åå¢å å¯¹å¶å®å¹³å°çæ¯æï¼ä½æ¯æè·³è¿é£ä¸æ­¥ï¼ä¸é¢æåçå½ä»¤ä¹é½è½æåï¼ä¸å¾å°ææ³è¦çç»æï¼å¯è§é£ä¸æ­¥åºè¯¥æ¯éå¿é¡»çï¼ææ¯ææ使ç¨ç Go çæ¬å·²é»è®¤æ¯æææå¹³å°ã

å°æ­¤è¿ç¯å³äºGolangå¨MacãLinuxãWindowsä¸å¦ä½äº¤åç¼è¯çå®ç°çæç« å°±ä»ç»å°è¿äº,æ´å¤ç¸å³Golang 交åç¼è¯å容请æç´¢èæ¬ä¹å®¶ä»¥åçæç« æ继续æµè§ä¸é¢çç¸å³æç« å¸æ大家以åå¤å¤æ¯æèæ¬ä¹å®¶ï¼

相关推荐