可以使用依赖项编译 Golang 代码吗?

huangapple go评论81阅读模式
英文:

Is it possible to compile golang code with dependencies?

问题

可以使用依赖项编译 Golang 代码吗?生成的可执行文件会很小吗?

英文:

Is it possible to compile golang code with dependencies? For an executable file was small.

答案1

得分: 2

如在“静态链接golang”(Vincent Batts)中提到:

只要被编译的源代码是纯Go语言,Go编译器将会静态链接可执行文件。
但是当你需要使用cgo时,编译器就必须使用外部链接器。

一个纯Go程序将显示如下:

$> go build ./code-pure.go
$> ldd ./code-pure
        不是动态可执行文件
$> file ./code-pure
./code-pure: ELF 64-bit LSB  可执行文件, x86-64, 版本 1 (SYSV), 静态链接, 未剥离

而使用cgo则不是这样的,除非你添加额外的标志,例如:

go build --ldflags '-extldflags "-static"' ./code-cgo.go
# 或者,使用gccgo
go build -compiler gccgo --gccgoflags "-static" ./code-cgo.go

请注意,即使在Go 1.5中(使用go进行编译,而不是gc),gccgo仍然存在

英文:

As mentioned in "Linking golang statically" (Vincent Batts):

> As long as the source being compiled is native go, the go compiler will statically link the executable.
Though when you need to use cgo, then the compiler has to use its external linker.

A pure go program will show like this:

$> go build ./code-pure.go
$> ldd ./code-pure
        not a dynamic executable
$> file ./code-pure
./code-pure: ELF 64-bit LSB  executable, x86-64, version 1 (SYSV), statically linked, not stripped

This isn't so with cgo, unless you add an extra flag like:

go build --ldflags '-extldflags "-static"' ./code-cgo.go
# or, with gccgo
go build -compiler gccgo --gccgoflags "-static" ./code-cgo.go

Reminder, even with Go 1.5 (which uses go for compilation, and not gc), gccgo will still be there.

huangapple
  • 本文由 发表于 2015年7月12日 03:22:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/31360907.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定