英文:
How do I add external executable to Go project
问题
我正在使用Go编写一个应用程序。然而,在每个平台上,我的代码将利用从另一个项目中编译的外部程序(例如,在Windows上使用C++,在Mac上使用Objective-C等)。这个外部可执行文件是通过os/exec
的exec.Command
函数调用的。
我可以成功地打包我的软件,但是有一个问题仍然存在,就是使用go run
会导致该文件丢失。
有没有办法告诉go
,每当我运行$ go run myproj
时,它应该包含外部文件(最好还能从源代码构建)?
据我所知,go run
只是在一个临时目录下构建二进制文件,但它不会包含任何外部文件,比如图片等。所以,例如当你有两个文件:$GOPATH/src/main/main.go
和$GOPATH/ext-tool.bin
,而main.go
的内容是:
package main
import "os/exec"
func main() {
cmd := exec.Command("./ext-tool.bin")
err := cmd.Run()
if err != nil {
os.Exit(1)
}
}
英文:
I am writing an application in Go. However on every platform my code will utilize external program compiled from another project in another language (e.g. C++ in Windows, Objective-C for Mac etc). This external executable is called with os/exec
exec.Command
function.
I can package my software with no problem, however one issue persists is that using go run
will result in this file missing.
Is there a way to tell go
that it should include external file (and preferably also build it from source) whenever I do $ go run myproj
?
AFAIK, go run
simply builds binary under a tmp directory, however it won't include any external files such as images etc. So for example when you have two files: $GOPATH/src/main/main.go
and $GOPATH/ext-tool.bin
and main.go
content is:
package main
import "os/exec"
func main() {
cmd := exec.Command("./ext-tool.bin")
err := cmd.Run()
if err != nil {
os.Exit(1)
}
}
答案1
得分: 3
一种替代方案是将可执行文件嵌入到应用程序构建中。
可以使用go-bindata
或其更近期的继任者unnoted/fileb0x
来实现。在这种情况下,您可以在内存文件系统中访问嵌入的可执行文件。
英文:
One alternative would be to embed your executable in your application build.
This is done with go-bindata
or its more recent successor unnoted/fileb0x
.
There, you would have access to your embedded executable within an in-memory filesystem.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论