You probably know that you can do better than just setting a breakpoint with a
filename:line number. You probably know that you can also set the breakpoint based on the function name.
But what if you have multiple functions with the same name, which can happen with statically defined functions in C and with overloaded functions in C++.
Let's look at an example in which there are two functions called
my_func. One takes a string and the other takes a long.
using namespace std;
cout << "String is " << str << endl;
cout << "Long is " << l << endl;
my_func("The meaning of life is");
We compile this with:
g++ funcs.cpp -g
Loading this into GDB and then TUI (Text User Interface) mode, I can then create a breakpoint with:
(gdb) break my_func
Breakpoint 2 at 0x5555555555551f1: my_func. (2 locations)
And with `info break` I can inspect the 2 breakpoint locations which shows the 2 locations under 2.1 and 2.2:
So if I run my program, I hit the first breakpoint location first and if I continue running, I hit the second.
Which results in:
... which helps me see which breakpoint was hit.
But suppose I want to have a breakpoint on just one of the locations. Starting again by deleting the breakpoints with `delete`
An extra hint is that typing tab will show completions. So hitting tab-tab at
break my_func( shows the two variants of the method:
Back to my new breakpoint (
break my_func(long)) I now have one breakpoint with one location. So this technique can be used for situations where you have statically defined functions in C and with overloaded functions in C++ (or any other situation with functions of the same name).
In the video, I also show how to create conditional breakpoints which allow you to determine when a breakpoint should be triggered rather than having it triggered every time.
For example, if we only want breakpoint 3 to be triggered if the variable l is 41 we do:
condition 3 l==41
In the example above, this would obviously never be triggered (since l always equals 42).
Another syntax which does the same thing and combined conditionals with our previous tip about identically named methods is:
break my_func(long) if l == 42
Another cool feature of GDB is the ability to use regex to specify breakpoints using `rbreak`. In the video, I show an example program which can be compiled, loaded into GDB and then using `rbreak`:
...which creates 2 breakpoints. This creates 2 breakpoints I can connect different commands and enable/disable them independently.
Receive Greg's fortnightly GDB tips & tricks directly in your inbox