:mannotop 2024 年 1 月 – manno的博客

月度归档: 2024 年 1 月

Golang RNG审查通过的洗牌实现

Introduce:

SFMT.h: This is the header file, which defines the interface for the RNG.

SFMT.c: This file contains the source code that implements the random number generator algorithm.

SFMT-params.h and SFMT-params19937.h: These files provide parameters for the Mersenne Twister  algorithm.

SFMT-common.h: Provides common or supportive functions for the algorithm

Knuth.go is used to implement shuffling

UniformIntDistribution.go is used to implement scaling

Go语言涉及CGO的交叉编译(跨平台编译)解决办法

这几天发现使用了cgo的服务在本地和ci上编译通过打包的容器无法正常在Docker上运行

exec <pkg name>: no such file or directory

查阅资料发现要使用交叉编译[1]来实现跨平台部署。

在没有CGO调用的情况下,交叉编译只需带上三个参数便可以实现

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build

显然对于带CGO的交叉编译,CGO_ENABLED必须开启。这也就需要辅助编译器来帮我们实现交叉编译了。

CGO_ENABLED=1 GOOS=linux GOARCH=amd64 CC=gcc CGO_LDFLAGS="-static" go build main.go

CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -ldflags '-s -w --extldflags "-static -fpic"' main.go

CGO_ENABLED 这个参数为1开启CGO。

GOOS 和 GOARCH 用来指定要构建的平台为Linux

通过CC=gcc 来指定GCC编译器。而CGO_LDFLAGS=”-static”来指定CGO部分的编译为静态编译。

可选参数-ldflags 是编译选项:

  • -s -w 去掉调试信息,可以减小构建后文件体积,
  • --extldflags "-static -fpic" 完全静态编译[2],这样编译生成的文件就可以任意放到指定平台下运行,而不需要运行环境配置。