如何从Golang创建一个在运行时不打开控制台窗口的可执行文件?

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

How do I create an executable from Golang that doesn't open a console window when run?

问题

我创建了一个应用程序,我希望它在后台无形地运行(没有控制台)。我该如何做到这一点?

(这是针对Windows的,在Windows 7 Pro 64位上进行了测试)

英文:

I created an application that I want to run invisibly in the background (no console). How do I do this?

(This is for Windows, tested on Windows 7 Pro 64 bit)

答案1

得分: 64

在线找到的文档说我可以使用类似以下的方式进行编译:

go build -ldflags -Hwindowsgui filename.go

但是这会报错:unknown flag -Hwindowsgui

在更新的(1.1?)编译器版本中,应该可以这样工作:

go build -ldflags -H=windowsgui filename.go

当我继续搜索时,我发现有一个注释说官方文档很快会更新,但与此同时,有很多旧式的示例答案会出错。

英文:

The documentation found online says I can compile with something along the lines of,

go build -ldflags -Hwindowsgui filename.go

But this gives an error: unknown flag -Hwindowsgui

With more recent (1.1?) versions of the compiler, this should work:

go build -ldflags -H=windowsgui filename.go

When I continued searching around I found a note that the official documentation should be updated soon, but in the meantime there are a lot of older-style example answers out there that error.

答案2

得分: 43

使用Go版本1.4.2

go build -ldflags "-H windowsgui"

来自Go文档:

go build [-o 输出] [-i] [构建标志] [包]

-ldflags '标志列表' 用于传递给每个5l、6l或8l链接器调用的参数。

英文:

Using Go Version 1.4.2

 go build -ldflags "-H windowsgui" 

> From the Go docs:
>
> go build [-o output] [-i] [build flags] [packages]
>
> -ldflags &#39;flag list&#39; arguments to pass on each 5l, 6l, or 8l linker invocation. <br>
>
>

答案3

得分: 12

如果您不想在调试过程中每次都输入冗长的构建指令,但仍希望控制台窗口消失,您可以在主函数的开头添加以下代码:

package main

import "github.com/gonutz/w32/v2"

func main() {
    console := w32.GetConsoleWindow()
    if console != 0 {
        _, consoleProcID := w32.GetWindowThreadProcessId(console)
        if w32.GetCurrentProcessId() == consoleProcID {
            w32.ShowWindowAsync(console, w32.SW_HIDE)
        }
    }
}

现在您可以使用go build进行编译。您的程序将在启动时短暂显示控制台窗口,然后立即隐藏它。

英文:

If you don't want to type the long build instructions every time during debugging but still want the console window to disappear, you can add this code at the start of your main function:

package main

import &quot;github.com/gonutz/w32/v2&quot;

func main() {
    console := w32.GetConsoleWindow()
    if console != 0 {
        _, consoleProcID := w32.GetWindowThreadProcessId(console)
        if w32.GetCurrentProcessId() == consoleProcID {
            w32.ShowWindowAsync(console, w32.SW_HIDE)
        }
    }
}

Now you can compile with go build. Your program will show the console window for a short moment on start-up and then immediately hide it.

huangapple
  • 本文由 发表于 2014年4月24日 00:43:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/23250505.html
匿名

发表评论

匿名网友

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

确定