golang 在 Mac、Linux、Window 下交叉编译

目录

  • 交叉编译
    • 参数说明
      • CGO_ENABLED
      • [GOOS : 目标操作系统【darwin、linux、windows】](#GOOS : 目标操作系统【darwin、linux、windows】)
      • [GOARCH :目标架构【386、amd64、arm】](#GOARCH :目标架构【386、amd64、arm】)
    • [Mac 下编译,Linux / Windows 下执行](#Mac 下编译,Linux / Windows 下执行)
    • [Linux 下编译,Mac / Windows 下执行](#Linux 下编译,Mac / Windows 下执行)
    • [Windows 下编译,Mac / Linux 下执行](#Windows 下编译,Mac / Linux 下执行)

Golang的交叉编译是指将Go程序从一个操作系统和架构编译为另一个操作系统和架构的过程。

也就是说我们可以在一个开发环境中编写代码,然后可以为多个不同的目标平台生成可执行文件。

交叉编译

参数说明

CGO_ENABLED

CGO 表示golang中的工具,CGO_ENABLED 表示CGO禁用,交叉编译中不能使用CGO

GOOS : 目标操作系统【darwin、linux、windows】

  • mac:darwin
  • linux:linux
  • windows:windows

GOARCH :目标架构【386、amd64、arm】

  • 386:也称 x86,对应 32 位操作系统
  • amd64:也称 x64,对应 64 位操作系统
  • arm:这种架构一般用于嵌入式开发。比如 Android、IOS、Win mobile、TIZEN 等

Mac 下编译,Linux / Windows 下执行

bash 复制代码
# Linux 下执行
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build main.go
# Windows 下执行
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go

Linux 下编译,Mac / Windows 下执行

bash 复制代码
# Mac 下执行
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build main.go
# Windows 下执行
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go

Windows 下编译,Mac / Linux 下执行

需要写一个批处理程序,在里面去设置,因为 Windows 下的 terminal 不支持shell

bash 复制代码
# Mac 下执行
SET CGO_ENABLED=0
SET GOOS=darwin
SET GOARCH=amd64
go build main.go
bash 复制代码
# Linux 下执行
SET CGO_ENABLED=0
SET GOOS=linux
SET GOARCH=amd64
go build main.go
相关推荐
bkspiderx几秒前
rpath:Linux 中固定共享库搜索路径的“永久解决方案”
linux·rpath·固定共享库搜索路径
wbs_scy2 分钟前
仿 muduo 高并发服务器项目:从 timerfd 到时间轮实现定时任务机制
linux·服务器·c++
AI的探索之旅3 分钟前
从 Ubuntu 14.04 到 24.04:TI AM335x 开发环境完整迁移与 Agent 接管方案
linux·数据库·嵌入式硬件·ubuntu·postgresql
阿pin16 分钟前
Android随笔-pipe是什么?
android·linux·pipe
小趴菜え20 分钟前
升级Ubuntu20.04版本至Ubuntu22.04
linux·运维
辰三26 分钟前
统信 UOS + GBase 8s 国产化环境部署实战:从虚拟机到数据库连接完整指南
linux·c#
Darkwanderor1 小时前
Linux进程优先级操作
linux·运维·c语言·c++
AOwhisky2 小时前
Linux(CentOS)系统管理入门笔记(第一期)——从 Multics 到主流发行版
linux·运维·笔记·centos·云计算
从零开始的代码生活_2 小时前
Linux epoll 多路转接详解
linux·运维·网络·后端·tcp/ip·计算机网络·php
渣渣盟2 小时前
Linux软件管理与编辑器命令速查手册
linux·运维·编辑器