Go编译源代码(Window环境)

Voryla · 2022-02-16 08:40:08 · 963 次点击 · 预计阅读时间 3 分钟 · 大约8小时之前 开始浏览    
这是一个创建于 2022-02-16 08:40:08 的文章,其中的信息可能已经有所发展或是发生改变。

Go编译源代码(Window环境)

[TOC]

1.gcc安装

1.1gcc下载

根据自己的系统选择gcc下载,笔者的系统为win10 64位 选择了x86_64-posix-seh

MinGW-w64 - for 32 and 64 bit Windows - Browse /mingw-w64/mingw-w64-snapshot at SourceForge.net

image-20220215220000804

1.2gcc安装

将下载后端压缩包解压到自己想放的位置,随后配置环境变量,指向bin目录即可

image-20220215220352346

可以使用 gcc -v 验证gcc是否安装成功

image-20220215220500806

2.Go源码安装

2.1下载Go源代码

git clone https://github.com/golang/go.git

2.2注意事项

  1. 1.5版本以后的Go编译需要本地已经安装过1.4版本以上的go,所以如果本机没有的话,请去下载一个 https://studygolang.com/dl/golang/go1.14.3.windows-amd64.msi

2.3安装完1.4后

设置环境变量

set CGO_ENABLED=0
set GOROOT_BOOTSTRAP=本地安装好的go路径,例如`C:\Go`
set GOROOT_FINAL=本地安装好的go路径,例如`C:\Go`

2.4安装Go源码

进入clone下来的Go源码中的src目录,执行 all.bat,耐心等待编译。

3.修改Go源码并调用

3.1修改源代码

比如修改 fmt.print.go 中的Println()函数

// Println formats using the default formats for its operands and writes to standard output.
// Spaces are always added between operands and a newline is appended.
// It returns the number of bytes written and any write error encountered.
func Println(a ...any) (n int, err error) {
    println("fmt") // 添加一行输出
    return Fprintln(os.Stdout, a...)
}

然后进入GO源码 src目录下,调用 make.bat 编译源码

image-20220215222005176

注意,编译完成后要修改GOROOT环境变量为GO源码所在的位置

image-20220215221447691

3.2 编写GO代码调用fmt.Println函数

为了方便可以将此.go文件放置在Go源码目录下的bin目录中

image-20220215221926435

package main

import "fmt"

func main() {
    fmt.Println("try")
}

3.3 使用编译后的源代码启动go文件

PS F:\GoLearnSource\go\bin> .\go.exe  run .\whatTest.go

调用成功

image-20220215222140758


有疑问加站长微信联系(非本文作者))

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

963 次点击  ∙  1 赞  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传