1. Simple packaging
program:
package main import "fmt" func main() { ("Hello World!") }
Pack:
# Execute the following 3 commands on the linux service#linux platform, generate main1 executable programCGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build # windows platform, generate executable programsCGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build # mac platform, generate main1 executable programCGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build
implement:
$ ./main1 Hello World!
2. Set values for variables in the program when packaging
program :
package main import "fmt" var ( VERSION string BUILD_TIME string GO_VERSION string ) func main() { ("%s\n%s\n%s\n", VERSION, BUILD_TIME, GO_VERSION) }
Packaging: The packaging method is the same as above. Here we only introduce the packaging under Linux.
# Execute the following command on the linux service#linux platform, generate main2 executable programCGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-X =1.0.0 -X 'main.BUILD_TIME=`date`' -X 'main.GO_VERSION=`go version`'"
implement:
# The output time is the time when packing$ ./main2 1.0.0 2023Year 06moon 14day Wednesday 10:13:06 CST go version go1.18.4 linux/amd64
3. Specify a name when packaging
# Generate linux-main1 executable fileCGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o linux-main1
$ ./linux-main1 Hello World!
There are other parameters when go build. If you need it, please check the relevant documents.
Summarize
This is the end of this article about Go Build compilation and packaging files. For more information about Go Build compilation and packaging files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!