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

ConsoleGo

Console Problem Overview


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)

Console Solutions


Solution 1 - Console

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.

Solution 2 - Console

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.
> >

Solution 3 - Console

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBart SilverstrimView Question on Stackoverflow
Solution 1 - ConsoleBart SilverstrimView Answer on Stackoverflow
Solution 2 - ConsoleShannon MatthewsView Answer on Stackoverflow
Solution 3 - ConsolegonutzView Answer on Stackoverflow