C++ debugging with gdb & bazel (& emacs)

Picaud Vincent picture Picaud Vincent · Aug 22, 2017 · Viewed 10.5k times · Source

I want to debug an executable generated with Bazel. The gdb debugger is lost with the links generated by Bazel and is not able to show me the C++ source code. How to fix that?

The project root directory is /home/.../Cpp/

./Cpp/
├── bazel-bin -> /home/picaud/.cache/bazel/_bazel_picaud...
├── bazel-Cpp -> /home/picaud/.cache/bazel/_bazel_picaud...
├── bazel-genfiles -> /home/picaud/.cache/bazel/_bazel_picaud...  
├── bazel-out -> /home/picaud/.cache/bazel/_bazel_picaud...   
├── bin
│   ├── BUILD
│   └── main.cpp
├── MyLib
│   ├── BUILD
│   ├── ....hpp
│   ├──  ...cpp
└── WORKSPACE

Answer

Picaud Vincent picture Picaud Vincent · Aug 22, 2017

The first step is to generate executables using the debug mode:

bazel build ... --compilation_mode=dbg -s

(the -s option is not mandatory it only shows the executed commands, you can remove it if you want)

gdb debugging from the command line:

You can start gdb with this command (from your project root directory):

gdbtui bazel-bin/bin/main

-> everything is okay, you should see your C++ source code.

The error would be to do:

cd bazel-bin/bin/
gdbtui main

In that case, because of the links, gdb is not able to retrieve the source code.

gdb debugging from Emacs:

Do as usual

M-x gdb 

In the emacs prompt define the complete absolute path to the executable:

gdb -i=mi /home/picaud/.../Cpp/bazel-bin/bin/main

Now in the gdb buffer you must tell gdb where to find source by defining your absolute path to the project root directory (where your WORKSPACE file is):

set directories /home/picaud/.../Cpp

Now the emacs gdb command should work properly and you can debug as usual.

(well this was an easy fix, just a note that maybe can help...)