C ++ debugging template with gdb

When I debug inside a function with a template,

  • How to find out the type of template that the current function uses?

    I tried p T He says gdb can not print type.

  • How can I break up a specific type of template?

    Suppose that the function foo<T>(...) has two possible forms: foo<int>(...) and foo<long>(...) . How to set a breakpoint so that gdb stops only on the first that uses int , but not the second that uses long ?

Edit: It would be nice if the breakpoint were given a line number. There are many good reasons for this, for example. the initial part of the function can take a lot of time, the place I want to debug may be inside the if , etc.

+5
source share
2 answers

You can use ptype instead of p to print the type. With recent enough (a couple of years) g ++ and gdb this will work.

Consider this source:

 #include <iostream> template<typename T> struct S { S(T t) { std::cout << t; } }; int main() { S<const char*> s2("hello"); S<int> s1(23); return 0; } 

Here I can enter the constructor for s2 and see T :

 (gdb) ptype T type = const char * 

Take a look at the current frame:

 (gdb) frame #0 S<char const*>::S (this=0x7fffffffe35f, t=0x400940 "hello") at q.cc:8 8 std::cout << t; 

I can set a breakpoint using the specified function name:

 (gdb) b S<const char *>::S Breakpoint 2 at 0x40087a: file q.cc, line 8. 
+3
source

To set a breakpoint for all instances, use:

 gdb> rbreak Foo<.*> 

To set only a breakpoint in a known instance

 gdb> break Foo<int> 

You can also use rbreak Foo<int> , but it doesn't make sense to use a call that evaluates regular expressions, but you don't give it rbreak Foo<int>

Code example:

 #include <iostream> #include <string> template < typename T> T Foo(T t) { return t; } int main() { std::cout << Foo<int>(1) << std::endl; std::cout << Foo<std::string>("Hallo") << std::endl; } 

Just compile with debug info:

 g++ main.cpp -g -o go 

Run gdb:

 gdb go 

And the test:

 gdb> rbreak Foo<int> gdb> run gdb> backtrace gdb> cont 

As you can see: only one instance of the template is affected.

In the opposite direction, you can see which instance of the template is being called:

 #0 Foo<int> (t=1) at main.cpp:5 #1 0x0000000000400b69 in main () at main.cpp:9 

As you can see, here is Foo<int> .

+3
source

Source: https://habr.com/ru/post/1235741/


All Articles