了解 go tool compile 和 link 命令
Understanding go tool compile and link commands
我知道将高级语言代码转换为机器语言或可执行代码涉及三个步骤,即编译、汇编和 linking。
根据 go docs go tool compile 执行以下操作 -
It then writes a single object file named for the basename of the first source file with a .o suffix
所以,最终的目标文件必须包含每个文件的机器语言代码(编译汇编后是运行)。如果我在 go 文件上传递 go tool compile -S,它会显示汇编语言 go generates.
在此之后,当我 运行 go tool link 目标文件时,它必须 link 所有需要的目标文件(如果多个) 然后生成最终的机器语言代码(基于 GOOS 和 GOARCH)。它生成一个文件 a.out
这里有几个基本问题 -
我如何知道哪些变量以及它们何时会在堆栈和堆中分配内存?如果我为一台机器生成可执行文件并在另一台具有不同体系结构的机器上生成 运行 是否重要?
我的测试程序
package main
func f(a *int, b *int) *int {
var c = (*a + *b);
var d = c;
return &d;
}
func main() {
var a = 2;
var b = 6;
f(&a,&b);
}
go tool compile -m -l test.go
的结果
test.go:6: moved to heap: d
test.go:7: &d escapes to heap
test.go:3: f a does not escape
test.go:3: f b does not escape
test.go:14: main &a does not escape
test.go:14: main &b does not escape
In which step is the memory getting allocated?
这取决于,一些在链接期间,一些在编译期间,大部分在 运行 时间(还有一些在加载期间)。
How do I know which variables and when are they going to be allocated memory in stack and heap?
特设你根本不知道。编译器决定这一点。如果编译器可以证明一个变量没有转义,它可能会将它保留在堆栈中。 Google 对于 "golang escape analysis"。如果您对它感兴趣,有一个标志 -m 可以让编译器输出他的决定。
Does it matter if I generate executable for one machine and run on another with different architecture?
不,只是因为这根本不起作用:可执行文件与架构相关,不会 运行 在不同的架构上。
您似乎混淆了 compilation/linking 和内存分配。后者与前两者截然不同。 (从技术上讲,您的链接程序可能包含内存,并且在加载过程中可能会获得更多内存,但这是高度技术性和特定于体系结构的,实际上无需担心)。
我知道将高级语言代码转换为机器语言或可执行代码涉及三个步骤,即编译、汇编和 linking。
根据 go docs go tool compile 执行以下操作 -
It then writes a single object file named for the basename of the first source file with a .o suffix
所以,最终的目标文件必须包含每个文件的机器语言代码(编译汇编后是运行)。如果我在 go 文件上传递 go tool compile -S,它会显示汇编语言 go generates.
在此之后,当我 运行 go tool link 目标文件时,它必须 link 所有需要的目标文件(如果多个) 然后生成最终的机器语言代码(基于 GOOS 和 GOARCH)。它生成一个文件 a.out
这里有几个基本问题 -
我如何知道哪些变量以及它们何时会在堆栈和堆中分配内存?如果我为一台机器生成可执行文件并在另一台具有不同体系结构的机器上生成 运行 是否重要?
我的测试程序
package main
func f(a *int, b *int) *int {
var c = (*a + *b);
var d = c;
return &d;
}
func main() {
var a = 2;
var b = 6;
f(&a,&b);
}
go tool compile -m -l test.go
的结果test.go:6: moved to heap: d
test.go:7: &d escapes to heap
test.go:3: f a does not escape
test.go:3: f b does not escape
test.go:14: main &a does not escape
test.go:14: main &b does not escape
In which step is the memory getting allocated?
这取决于,一些在链接期间,一些在编译期间,大部分在 运行 时间(还有一些在加载期间)。
How do I know which variables and when are they going to be allocated memory in stack and heap?
特设你根本不知道。编译器决定这一点。如果编译器可以证明一个变量没有转义,它可能会将它保留在堆栈中。 Google 对于 "golang escape analysis"。如果您对它感兴趣,有一个标志 -m 可以让编译器输出他的决定。
Does it matter if I generate executable for one machine and run on another with different architecture?
不,只是因为这根本不起作用:可执行文件与架构相关,不会 运行 在不同的架构上。
您似乎混淆了 compilation/linking 和内存分配。后者与前两者截然不同。 (从技术上讲,您的链接程序可能包含内存,并且在加载过程中可能会获得更多内存,但这是高度技术性和特定于体系结构的,实际上无需担心)。