Compilation and usage of go language static libraries

  • 2020-10-23 21:00:28
  • OfStack

This paper mainly introduces the compilation and use of go language static library. Taking windows platform as an example, step 1 of linux platform is as follows:


>echo %GOPATH%
E:\share\git\go_practice\

>echo %GOROOT%
C:\Go\

>tree /F %GOPATH%\src
 volume  work  The folder  PATH  The list of 
 Volume serial number is  0009-D8C8
E:\SHARE\GIT\GO_PRACTICE\SRC
 │  main.go
 │ 
 └ ─ demo
    demo.go

In the %GOPATH%\src directory, there are demo packages and main. go, main. go applications using demo packages as follows:


package main
import "demo"
func main() {
  demo.Demo()
}

The demo. go code in the demo package is as follows:


package demo

import "fmt"

func Demo() {
  fmt.Println("call demo ...")
}

Since demo.go is 1 package under %GOPATH%\src directory, main.go can be used directly after import, run ES31en.go:


>go run main.go
call demo ...

Now, we need to compile demo.go into static library demo.a. We do not provide the source code of ES40en.go, so that main.go can compile and run normally. The detailed steps are as follows:

1 Compile static library demo.a

[

> go install demo

]

Running the go install demo command from the command line will generate the corresponding static library file demo.a in the %GOPATH% directory (windows platform 1 normally in the %GOPATH%\src\pkg\windows_amd64 directory).

2 compile main go

Enter the directory of ES74en. go and compile ES76en. go:

[

> go tool compile -I E:\share\git\go_practice\pkg\windows_amd64 main.go

]

The -ES86en option specifies the installation path for the demo package for the ES88en.go import, which is E:\share\git\go_practice\pkg\win
dows_amd64 directory, the corresponding target file main.o will be generated after successful compilation.

3 links main. o

[

> go tool link -o main.exe -L E:\share\git\go_practice\pkg\windows_amd64 main.o

]

The -ES114en option specifies the path to the static library ES115en.a, which is E:\share\git\go_practice\pkg\win
dows_amd64 directory, the corresponding executable main.exe will be generated after successful linking.

4 run main. exe

[

> main.exe
call demo ...

]

Now, even if you delete the demo directory and compile the link main.go again, it will generate main.exe correctly


>go tool compile -I E:\share\git\go_practice\pkg\windows_amd64 main.go

>go tool link -o main.exe -L E:\share\git\go_practice\pkg\windows_amd64 main.o

>main.exe
call demo ...

However, if you delete the static library ES151en.a, you cannot compile ES153en.go, as follows:


>go tool compile -I E:\share\git\go_practice\pkg\windows_amd64 main.go
main.go:3: can't find import: "demo"

The above is the compilation and use method of go language static library. Next time, I will introduce the compilation and use method of dynamic library.

conclusion


Related articles: