Cross-compilation problem with Golang

Reference: Golang cross-compiles binaries for various platforms

Today, I am going to deploy a Golang project developed on a Mac to a cloud server for deployment, so I compiled the project into a Unix executable binary file under mac through go build and uploaded it to the CentOS cloud server to prepare for running, but an error was reported at this time. :

-bash: ./Technology-Learning-Community: cannot execute binary file

After inquiries, there are generally two reasons for this situation:

  • One is the lack of execution permissions , so I tried to increase the permissions through sudo execution and chmod +x, but still can't solve it.
  • The second is the difference in the compilation environment. The binary files under mac are incompatible with those under linux. After constant inquiry of the problem, I learned the concept of cross-compilation in Golang .

The so-called cross-compilation is to generate an executable program for another platform on one platform, which is one of the reasons why Golang can achieve portability. We can easily generate binaries for other platforms by setting the compilation parameters before go build:

# mac上编译linux和windows二进制
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build main.go
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go

# linux上编译mac和windows二进制
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build main.go
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go

# windows上编译mac和linux二进制
SET CGO_ENABLED=0 SET GOOS=darwin SET GOARCH=amd64 go build main.go
SET CGO_ENABLED=0 SET GOOS=linux SET GOARCH=amd64 go build main.go

The three variables used are the configuration parameters in go env. We can go help environmentview the detailed meaning of the parameters:

  • CGO_ENABLED: Whether to enable CGO, CGO calls C code cross-compilation in Go code, but cross-compilation does not support CGO, that is to say, if there is C code in your code, it cannot be compiled, so you need to disable it

    Whether the cgo command is supported,Either 0 or 1

  • GOOS: Specifies the operating system of the target platform

    The operating system for which to compile code,Examples are linux, darwin, windows, netbsd

  • GOARCH: Executes the operating system architecture of the target platform

    The architecture, or processor, for which to compile code,Examples are amd64, 386, arm, ppc64.

Guess you like

Origin blog.csdn.net/qq_45173404/article/details/122618080