Home > Backend Development > Golang > How to Build Multiple Go Binaries Simultaneously?

How to Build Multiple Go Binaries Simultaneously?

Barbara Streisand
Release: 2024-11-02 01:46:31
Original
532 people have browsed it

How to Build Multiple Go Binaries Simultaneously?

Building Multiple Package Binaries Simultaneously

As per your inquiry, building multiple package binaries simultaneously can be achieved by creating a top-level "cmd" folder structure, which has been suggested elsewhere. However, you have encountered challenges with this approach.

To build individual binaries using a "cmd" folder structure:

  1. Ensure that you have the following file structure (as per your working example):

    ├── cmd
    │   ├── bin1
    │   │   └── main.go
    │   ├── bin2
    │   │   └── main.go
    ├── src
    │   ├── shared
    │   │   ├── foo
    │   │   │   └── foo.go
    Copy after login
  2. Navigate to the project's root directory.
  3. Execute the following command for each binary you wish to build, replacing "" with the desired binary name:

    go build -o "<binary-name>" ./cmd/<binary-name>
    Copy after login

For example:

go build -o bin1 ./cmd/bin1
go build -o bin2 ./cmd/bin2
Copy after login

This will create the "bin1" and "bin2" binaries in the project's root directory.

Alternative Approach Using a Script

If you prefer not to install the binaries into $GOPATH/bin, you can create a build script that iterates over the packages and builds each binary individually.

  1. Create a script named "build-all.sh" with the following contents:

    <code class="sh">#!/bin/bash
    
    # Iterate over the packages in the "cmd" directory
    for CMD in `ls cmd`; do
    
      # Build the binary for each package
      go build -o $CMD ./cmd/$CMD
    done</code>
    Copy after login
  2. Make the script executable:

    <code class="sh">chmod +x build-all.sh</code>
    Copy after login
  3. Run the script to build all binaries in one step:

    <code class="sh">./build-all.sh</code>
    Copy after login

This approach provides flexibility and control over the binary build process and mimics what many open source projects use.

The above is the detailed content of How to Build Multiple Go Binaries Simultaneously?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template