I have been using Go and have read at some places that Go compiler needs to only include the packages that you are importing directly from main
.
As a result, the time it takes to resolve dependency is linear as compared to C++ where its exponential.
How does that work?
If main
imports package alpha
which in turn imports package beta
then wouldn't Go compiler need to compile the whole tree?
为什么Go编译器只需要包含您直接导入的软件包?
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- dongyuan8469 2019-02-17 14:28关注
The Go compiler first compiles a single package into a single object file. At this stage, it only needs to resolve all the
import
s it finds in the package it compiles. For the object file of your package, there are only calls to the same package or direct imports, so there's no issue here. A separate linking stage links all object files together. There's a decent explanation of this in the doc of the compile package:Compile, typically invoked as “go tool compile,” compiles a single Go package comprising the files named on the command line. It then writes a single object file named for the basename of the first source file with a .o suffix. The object file can then be combined with other objects into a package archive or passed directly to the linker (“go tool link”). If invoked with -pack, the compiler writes an archive directly, bypassing the intermediate object file.
The generated files contain type information about the symbols exported by the package and about types used by symbols imported by the package from other packages. It is therefore not necessary when compiling client C of package P to read the files of P's dependencies, only the compiled output of P.
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报