Home > Backend Development > Golang > 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
Release: 2024-11-03 09:00:30
Original
383 people have browsed it

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>
Copy after login

This script will result in the following:

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

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
Copy after login

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>
Copy after login

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!

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