I spent the vast majority of my time in the last 4 years writing, reading and debugging Python or JavaScript code. The process of learning Go was like a beautiful hike in the mountains with a small rock in my shoe. A lot of things impressed me, but using println to debug my code was travelling too far into the past. In Python we have pdb/@ipdb@ to debug the code while running it, JavaScript offers similar tools. Over the years this pattern became a very important part of my development workflow.
Today I realized that Go has builtin support for the Gnu debugger.
For the sake of this article we are going to use the simple program below:
To use <span class="caps">GDB</span> you need to compile your program with the options -gcflags "-N -l". These options prevent the compiler from using inline functions and variables.
Here is an example of an interactive debugging GDB session:
First we run our program:
Now that we know how to run our program we probably want to set a breakpoint:
Once GDB stops at your breakpoint you view the context:
You can also inspect the variables:
Earlier in the code we started a goroutine. I want to introspect this part of my program next time we execute the line 10.
The last thing we are going to demo today is how to change the value of a variable at runtime.
We only covered the following commands:
list
next
print
continue
break <line number>
whatis
set variable <var>=<value>
…and this barely scratches the surface of what you can do with GDB, here are some links if you want to learn more:
http://sourceware.org/gdb/current/onlinedocs/gdb/
http://golang.org/doc/gdb
About the author
Yann Malet
Yann builds and architects performant digital platforms for publishers. In 2015, Yann co-authored High-Performance Django with Peter Baumgartner.
Prior to his involvement with Lincoln Loop, Yann focused on Product Lifecycle Management systems (PLM) for several large …