63

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)

2
  • 1
    possible duplicate of Is there a windowed setting option for the Go compiler?
    – kostix
    Apr 23, 2014 at 17:13
  • @kostix When I did a search for having no console, it didn't show up. But the flag you're pointing to is in that answer, you're right, I think, although the syntax is still slightly different and I wasn't looking for a "windowed option". Apr 23, 2014 at 18:35

3 Answers 3

64

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
  • 1
    From: golang.org/cmd/link On Windows, -H windowsgui writes a "GUI binary" instead of a "console binary."
    – colm.anseo
    Oct 11, 2019 at 14:00
  • Hi, do you know what flag would achieve the same on macOS and linux?
    – None
    Jun 29, 2021 at 18:51
45

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.

1
  • Don't forget you might need to include your filename.go as a parameter. In v1.10.1 the following syntax also works; go build -ldflags -H=windowsgui filename.go.
    – Aaron
    Apr 26, 2018 at 3:16
13

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.