Home  >  Article  >  Backend Development  >  How Can I Build a Library and a Standalone Binary with the Same Name in Go?

How Can I Build a Library and a Standalone Binary with the Same Name in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-11-27 01:25:09379browse

How Can I Build a Library and a Standalone Binary with the Same Name in Go?

Multiple Libraries and Binaries with Identical Names

This question explores the possibility of creating a library and a standalone binary with the same name. The example of the Tar command-line tool and its library functionality demonstrates this scenario.

Initially, the user attempted the following directory structure:

src/
    tar/
        tar.go # belongs to package tar
        main.go # imports tar and provides a main function

However, this resulted in a "command" called tarbin, not the desired tar command.

To address this, the user employed the workaround of explicitly specifying the output binary name using go build -o $GOPATH/bin/tar tar.

A more elegant solution suggested by the responder is to organize the code as follows:

src/
    tar/
        tar.go         # tar libary
        tar/
            main.go    # tar binary

Using this structure, the resulting binary will be named tar, while the library is named tar.

If the code is hosted on GitHub, the directory structure would be as follows:

src/
    github.com/
        you/
            tar/
                tar.go         # tar libary
                tar/
                    main.go    # tar binary

This organization ensures that the go command can install both the binary and the library when used with go get install github.com/you/tar/tar.

The advantage of this approach is that it allows for building and testing all the code in the project using go install ./....

The above is the detailed content of How Can I Build a Library and a Standalone Binary with the Same Name in Go?. 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