How do I debug a Go program? I have been using the Gedit Go IDE, but it doesn't have debugging. Is there a way to step though my code and inspect memory? Or am I stuck with print statements? Can I use OutputDebugString?
To debug a program, execute the dlv debug command. Attach the filename at the end of this command, and debugging will start. For example, if you want to debug the main.go file, run the command dlv debug main.go . It is also known as “delve server” because this is a running process waiting for instructions.
You can generate uncompressed debug information by using go build -ldflags=-compressdwarf=false . (For convenience you can put the -ldflags option in the GOFLAGS environment variable so that you don't have to specify it each time.)
To access breakpoint intentions, place the caret at the line with the breakpoint and press Alt+Enter . Use this option when you need to quickly configure basic breakpoint properties. To access the full list of properties, right-click the breakpoint and click More or press Ctrl+Shift+F8 .
Update: There is now an official page in the docs on Debugging Go Code with GDB. Much has changed since this answer was written, and several of the limitations listed below have been removed. I'm leaving the rest of this answer for posterity, but if you want to debug Go code, follow the link above.
The Go linkers now emit DWARF debugging symbols that can be interpreted by gdb version 7.x.
Highlight from the blog post linked above:
You can...
There are still some inconveniences:
Some things don't work:
New initiative (started May 2014): derekparker/delve
, now (2021): go-delve/delve:
Delve is a Go debugger, written in Go.
(mainly for Linux though, OsX support is coming, Windows supportunknownsupported in 2016)
- Attach to an already running process
The debugger can be launched in three ways:
Compile, run, and attach in one step:
$ dlv -run
Provide the name of the program you want to debug, and the debugger will launch it for you.
$ dlv -proc path/to/program
Provide the pid of a currently running process, and the debugger will attach and begin the session.
$ sudo dlv -pid 44839
Delve can insert breakpoints via the breakpoint command once inside a debug session, however for ease of debugging, you can also call
runtime.Breakpoint()
and Delve will handle the breakpoint and stop the program at the next source line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With