How to `print`/evaluate c++ template functions in gdb

前端 未结 1 1002
情深已故
情深已故 2021-01-18 01:52

I was wondering if it is possible to use gdb print command to evaluate results of c++ template functions. In the following code with a simple id fu

1条回答
  •  时光说笑
    2021-01-18 02:10

    Without an explicit instance in the source code, the compiler will treat the template code as it would "static inline" code and optimize it out if it is unused. An explicit instance will create a symbol with external linkage (although it could still be technically optimized away by the linker, but in my test it did not...):

    template
    T id(T x) {return x;}
    
    template int id (int x);
    
    int main() {
      int i = 0;
      i = i + 1;
    } 
    

    Within gdb, I place the C++ function I want to call within single quotes:

    Breakpoint 1, main () at tmpl.cc:7
    7     int i = 0;
    (gdb) n
    8     i = i + 1;
    (gdb) p i
    $1 = 0
    (gdb) p 'id(int)'(i)
    $2 = 0
    (gdb)
    

    Your question in your comment about creating an explicit instance of a variadic template, the syntax is the same. You have to create a different explicit instance for each different parameter list you plan to call the template with.

    0 讨论(0)
提交回复
热议问题