How does go compile packages in program?

Imagine you are on a project, which have 3 files named:

init.go
main.go
helper.go

each and every file is using the package fmt.

now the question is “will go compile the same package for 3 times? or just for once?”

And the other scenario is the package fmt uses the package io in itself.

So if I use io again in my program when i am importing fmt

will it compile the package io twice? or just once?

1 Like

The Go installer installs compiled library files for the Go packages. On my Mac, these library files include

/usr/local/go/pkg/darwin_amd64/fmt.a
/usr/local/go/pkg/darwin_amd64/io.a

The go tool will compile your code and then link the result with the used libraries to generate the executable binary.

The fmt and io packages are not compiled at all when you build your program.

Edit: Of coures the Go installer also installs the source files. On my system these include

/usr/local/go/src/fmt/
|-- doc.go
|-- example_test.go
|-- export_test.go
|-- fmt_test.go
|-- format.go
|-- print.go
|-- scan.go
|-- scan_test.go
`-- stringer_test.go

and

/usr/local/go/src/io
|-- example_test.go
|-- io.go
|-- io_test.go
|-- ioutil
|   |-- example_test.go
|   |-- ioutil.go
|   |-- ioutil_test.go
|   |-- tempfile.go
|   |-- tempfile_test.go
|   `-- testdata
|       `-- hello
|-- multi.go
|-- multi_test.go
|-- pipe.go
`-- pipe_test.go

But since the compiled library files (.a) already exist, the source files do not have to be compiled when your program is build.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.