golang gdb支持编译及调试

如何编译支持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,编译的时候带上 -gcflags "-N-l"; 采用如下编译的例子,就可以使用gdb调试该golang代码了:

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 =

参考文献

  1. https://astaxie.gitbooks.io/build-web-application-with-golang/content/en/11.2.html
posted @ 2022-04-16 11:04  staylight  阅读(453)  评论(0编辑  收藏  举报