我可以有一个图书馆和二进制具有相同名称? [英] Can I have a library and binary with the same name?
问题描述
我建立一个图书馆,但我也希望它是可作为一个独立的二进制文件。
例如,假设我建立焦油的实现。焦油通常被用作命令,但它也可以用来作为一个库。直觉上,我会做这样的事情:
的src /
柏油/
tar.go#属于焦油打包
main.go#进口沥青,并提供主要功能
这似乎并没有工作,虽然。从文档,似乎命令应该从库中一个独立的名字。适应给有这个例子的例子中,我有以下的目录结构:
的src /
柏油/
tar.go#属于焦油打包
tarbin /
main.go#进口沥青,并提供主要功能
不过,这会 tarbin
,而不是焦油
在 $ GOPATH /称为命令斌
。我已经找到了解决办法是做去打造-o $ GOPATH /斌/焦油焦油
,但我得到我在做什么可怕的错误的感觉。有没有更好的办法?
注意:我清楚地知道,焦油
包含在标准库,我只使用它作为一个例子<。 / p>
我可能会做到这一点。
的src /
柏油/
tar.go#焦油libary
柏油/
main.go#焦油二进制
这会给你一个名为焦油
二进制文件和一个名为库焦油
假设你是在github主办这次那么你会希望
的src /
github.com/
您/
柏油/
tar.go#焦油libary
柏油/
main.go#焦油二进制
这将使你当你做一个二进制称为焦油去拿安装github.com/you/tar/tar
和一个名为库 github上.COM /你/焦油
当你做去拿安装github.com/you/tar
根据您觉得更重要的是,你可以交换库和二进制超过
的src /
github.com/
您/
柏油/
main.go#焦油二进制
柏油/
tar.go#焦油libary
将所有的code在一棵树,可以执行去从根本上安装./...
来构建所有的包和子包是一个优势。 去测试| FMT ./...
也。 (请注意,真的是3点!)
I'm building a library, but I also want it to be usable as a standalone binary.
For example, let's say I'm building an implementation of Tar. Tar is commonly used as a command, but it can also be used as a library. Intuitively, I'd do something like this:
src/
tar/
tar.go # belongs to package tar
main.go # imports tar and provides a main function
This doesn't seem to work though. From the documentation, it seems that "commands" should have a separate name from the library. Adapting the example given there to this example, I have the following directory structure:
src/
tar/
tar.go # belongs to package tar
tarbin/
main.go # imports tar and provides a main function
However, this creates a command called tarbin
, not tar
in $GOPATH/bin
. The workaround I've found is to do go build -o $GOPATH/bin/tar tar
, but I get the feeling I'm doing something horribly wrong. Is there a better way?
Note: I'm well aware that tar
is included in the standard libs, I'm only using it as an example.
I'd probably do this
src/
tar/
tar.go # tar libary
tar/
main.go # tar binary
That will give you a binary called tar
and a library called tar
Let's say you are hosting this on github then you'd want
src/
github.com/
you/
tar/
tar.go # tar libary
tar/
main.go # tar binary
Which would give you a binary called tar when you do go get install github.com/you/tar/tar
and a library called github.com/you/tar
when you do go get install github.com/you/tar
Depending on which you feel is more important you could swap the library and the binary over
src/
github.com/
you/
tar/
main.go # tar binary
tar/
tar.go # tar libary
Keeping all the code in one tree enables you to do go install ./...
from the root to build all packages and subpackages which is an advantage. go test|fmt ./...
also. (Note that really is 3 dots!)
这篇关于我可以有一个图书馆和二进制具有相同名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!