Golang debug using GDB?

Golang now works well with GDB

Here is an example golang app gdbtest

- gdbtest/
  - main.go

Take the following example main.go

package main

import "fmt"

type MyStruct struct {
    x string
    i int
    f float64
}

func main() {
    x := "abc"
    i := 3
    fmt.Println(i)
    fmt.Println(x)

    ms := &MyStruct{
        x: "cba",
        i: 10,
        f: 11.10335,
    }
    fmt.Println(ms)
}

Save that to main.go. Then compile with the follwing gcflag flag.

go build -gcflags "-N"

Open gdb with your newly built golang app

gdb gdbtest
# or 
gdb <PROJECT_NAME>

You now have full control of gdb. For example, add a breakpoint with br <linenumber> command, then execute the app with run

(gdb) br 22
Breakpoint 1 at 0x2311: file /go/src/github.com/cevaris/gdbtest/main.go, line 22.
(gdb) run
Starting program: /go/src/github.com/cevaris/gdbtest/gdbtest
3
abc

Breakpoint 1, main.main () at /go/src/github.com/cevaris/gdbtest/main.go:22
22              fmt.Println(ms)
(gdb)

Now you can print all the local variables

(gdb) info locals
i = 3
ms = 0x20819e020
x = 0xdb1d0 "abc"

Even get access to the pointers

(gdb) p ms
$1 = (struct main.MyStruct *) 0x20819e020
(gdb) p *ms
$2 = {x = 0xdb870 "cba", i = 10, f = 11.103350000000001}

Go does not work well with GDB and one of the known problems is the printing of values.

More details can be found here.

Tags:

Gdb

Go