英文:
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 'flag list'
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 "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)
}
}
}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论