如何将外部可执行文件添加到Go项目中?

huangapple go评论73阅读模式
英文:

How do I add external executable to Go project

问题

我正在使用Go编写一个应用程序。然而,在每个平台上,我的代码将利用从另一个项目中编译的外部程序(例如,在Windows上使用C++,在Mac上使用Objective-C等)。这个外部可执行文件是通过os/execexec.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.

huangapple
  • 本文由 发表于 2017年1月7日 23:40:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/41523148.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定