"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Build Multiple Go Package Binaries Simultaneously Without a Top-Level `cmd` Folder?

How to Build Multiple Go Package Binaries Simultaneously Without a Top-Level `cmd` Folder?

Published on 2024-11-11
Browse:311

How to Build Multiple Go Package Binaries Simultaneously Without a Top-Level `cmd` Folder?

Building Multiple Go Package Binaries Simultaneously

The question revolves around building multiple package binaries simultaneously, as the default advice of using a top-level cmd folder doesn't seem to work. The provided code example shows a particular folder structure that enables building specific binaries correctly.

To build all binaries in one step using the go build command, a variation of the following is recommended:

cd $GOPATH/someProject
for CMD in `ls src/cmd`; do
  go build ./src/cmd/"$CMD"
done

This command iterates through the packages in the src/cmd directory and builds each package individually. The resulting binaries will be stored in their respective package directories.

Alternatively, if you don't wish to install the binaries into $GOPATH/bin, a script can be employed. This is a common practice in open source projects, where build scripts handle multiple binary production.

The following example script can be used:

cd $GOPATH/someProject
for CMD in `ls cmd`; do
  go build ./cmd/$CMD
done

This script iterates through the packages in the cmd directory and runs go build on each. The result is a set of binaries stored in their respective cmd package directories.

For further reference, the following popular projects provide examples of build scripts:

  • Grafana: https://github.com/grafana/grafana/blob/master/build.go
  • Torus: https://github.com/coreos/torus/blob/master/Makefile
  • Caddy: https://github.com/mholt/caddy/blob/master/dist/automate.go
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3