Home  >  Article  >  Backend Development  >  Why Doesn\'t the Default Advice of Using a Top-Level Cmd Folder Work for Building Multiple Binaries?

Why Doesn\'t the Default Advice of Using a Top-Level Cmd Folder Work for Building Multiple Binaries?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 09:00:30338browse

Why Doesn't the Default Advice of Using a Top-Level Cmd Folder Work for Building Multiple Binaries?

Building Multiple Package Binaries in a Single Command

In order to build multiple package binaries in one go, you need to create a script to iterate through each package and run the go build command on each one, as shown below:

<code class="bash">cd $GOPATH/someProject
for CMD in `ls cmd`; do
  go build ./cmd/$CMD
done</code>

This script will result in the following:

[root@node1 test]# ls $GOPATH/someProject
bin1  bin2  cmd

Why the Default Advice of Using a Top-Level Cmd Folder Doesn't Work

The default advice of using a top-level cmd folder for building multiple binaries does not work because the go build command does not recognize the cmd folder as a package. Instead, it treats the cmd folder as a subdirectory of the current working directory and only builds the package contained within that directory. This results in only one binary being built.

Alternative Solution: Using a Make File or Build Script

If you do not want to install the binaries into $GOPATH/bin, you can create a make file or build script to manage the build process. Most open-source projects use this approach to produce multiple binaries. For example:

Make File:

# Makefile for building multiple binaries

all: bin1 bin2

bin1:
    go build ./cmd/bin1

bin2:
    go build ./cmd/bin2

Build Script:

<code class="bash">#!/bin/bash

# Iterate over the packages in cmd and run go build on each
for CMD in `ls cmd`; do
  go build ./cmd/$CMD
done</code>

The above is the detailed content of Why Doesn\'t the Default Advice of Using a Top-Level Cmd Folder Work for Building Multiple Binaries?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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