温馨提示×

golang如何在ubuntu编译

小樊
47
2026-10-24 23:06:18
栏目: 编程语言

在 Ubuntu 上编译 Go(Golang)程序,通常有两种场景:编译已经写好的 Go 代码 和 从源码编译 Go 工具链本身。下面分别说明。


一、编译已有的 Go 程序(最常见)

1. 安装 Go 环境

sudo apt update
sudo apt install golang-go -y

验证:

go version

如果 apt 版本太旧,建议从官网下载最新版: https://go.dev/dl/

2. 编写示例程序

mkdir hello && cd hello
nano main.go
package main

import "fmt"

func main() {
    fmt.Println("Hello, Ubuntu!")
}

3. 编译

go build

会生成可执行文件:

./hello

4. 交叉编译(可选)

例如编译 Linux 64 位:

GOOS=linux GOARCH=amd64 go build

二、从源码编译 Go 本身(不常用)

1. 安装依赖

sudo apt install git gcc make -y

2. 下载 Go 源码

git clone https://go.googlesource.com/go
cd go
git checkout go1.22.0  # 指定版本

3. 编译

cd src
./make.bash

编译完成后:

../bin/go version

三、常见问题

1. go: command not found

说明 Go 没装好或 PATH 没配置:

export PATH=$PATH:/usr/local/go/bin

2. 模块问题

go mod init hello
go mod tidy

如果你是想交叉编译 Windows / macOS 程序,或者在 Docker 里编译,可以告诉我具体需求。

0 踩