Home > Backend Development > Golang > 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
Release: 2024-11-27 01:25:09
Original
437 people have browsed it

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

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

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

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!

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