如何编译支持gdb调试的golang程序

首先,gdb的版本要高于7.1

其次,在编译golang程序时,需要注意以下2点

When compiling Go programs, the following points require particular attention:

1. Using -ldflags "-s" will prevent the standard debugging information from being printed
2. Using -gcflags "-N-l" will prevent Go from performing some of its automated optimizations 
   -optimizations of aggregate variables, functions, etc. These optimizations can make it very difficult 
   for GDB to do its job, so it's best to disable them at compile time using these flags.
-ldflags-s
package main

import (
    "fmt"
    "time"
)

func counting(c chan<- int) {
    for i := 0; i < 10; i++ {
        time.Sleep(2 * time.Second)
        c <- i
    }
    close(c)
}

func main() {
    msg := "Starting main"
    fmt.Println(msg)
    bus := make(chan int)
    msg = "starting a gofunc"
    go counting(bus)
    for count := range bus {
        fmt.Println("count:", count)
    }
}

假设以上golang文件名为gdbfile.go

go build -gcflags "-N -l" gdbfile.go

调用方式如下:

gdb gdbfile

常用gdb命令

  • list

    列出当前文件内容

  • print

    打印指定的参数

  • break

    添加断点

  • delete

    删掉断点

  • backtrace

    打印

  • info

  • info breakpoints

  • info goroutines

  • set variable

    This command is used to change the value of a variable in the process. It can be used like so: set variable =

参考文献