packagemainimport("fmt""time")var(// 全局变量,用于演示查看全局变量globalMessage="Hello from a global variable!")// aSimpleFunction 是一个简单的函数,用于演示函数调用和局部变量funcaSimpleFunction(nint)int{// 局部变量result:=n*nfmt.Printf("Inside aSimpleFunction: calculated result is %d\n",result)returnresult}funcmain(){fmt.Println("Program starting...")// 局部变量loopCounter:=5fori:=0;i<loopCounter;i++{fmt.Printf("Main loop, iteration %d\n",i)// 调用函数square:=aSimpleFunction(i)fmt.Printf("The square of %d is %d\n",i,square)time.Sleep(1*time.Second)}fmt.Println(globalMessage)fmt.Println("Program finished.")}
-rwxr-xr-x 1 user user 2.1M Aug 10 17:30 my-app # 原始文件 (最大)
-rw-r--r-- 1 user user 650K Aug 10 17:31 my-app.sym # 符号文件 (只包含调试信息)
-rwxr-xr-x 1 user user 1.5M Aug 10 17:31 my-app.stripped # 精简后的可执行文件 (最小)
GDB 启动时,会自动读取 .gnu_debuglink 段,找到并加载 my-app.sym。你会看到类似 “Reading symbols from ./my-app.sym…” 的提示。
现在,你可以像调试普通程序一样进行操作了。
GDB 调试会话示例:
bash
$ gdb ./my-app.stripped
GNU gdb (GDB) 12.1
...
Reading symbols from ./my-app.stripped...
Reading symbols from ./my-app.sym... # <--- 看这里,GDB 自动加载了符号文件(gdb)# 在 aSimpleFunction 函数入口处设置一个断点(gdb) b main.aSimpleFunction
Breakpoint 1 at 0x48d2b0: file /path/to/your/project/main.go, line 15.
# 运行程序(gdb) run
Starting program: /path/to/your/project/my-app.stripped
Program starting...
Main loop, iteration 0Inside aSimpleFunction: calculated result is 0The square of 0 is 0Breakpoint 1, main.aSimpleFunction (n=1) at /path/to/your/project/main.go:15
15 func aSimpleFunction(n int) int {# 查看传入的参数 n(gdb) p n
$1=1# 单步执行到下一行(gdb) next
17 result := n * n
# 查看局部变量 result 的值(gdb) p result
$2=1# 查看全局变量(gdb) p main.globalMessage
$3="Hello from a global variable!"# 继续执行(gdb)continueContinuing.
Inside aSimpleFunction: calculated result is 1The square of 1 is 1Breakpoint 1, main.aSimpleFunction (n=2) at /path/to/your/project/main.go:15
15 func aSimpleFunction(n int) int {# 退出 GDB(gdb) quit
A debugging session is active.
Inferior 1[process 12345] will be killed.
Quit anyway? (y or n) y
We use cookies and similar methods to recognise visitors and remember preferences. We also use them to measure
campaign effectiveness and analyse site traffic.
By selecting 'Accept', you consent to the use of these methods by us and trusted third parties.