【问题标题】:How to `print`/evaluate c++ template functions in gdb如何在 gdb 中“打印”/评估 C++ 模板函数
【发布时间】:2014-07-25 13:52:36
【问题描述】:

我想知道是否可以使用 gdb print 命令来评估 c++ 模板函数的结果。在下面带有简单id 函数的代码中,我尝试了printid(x) 结果,但好像idid<t> 从未存在过。我使用的代码如下,用g++ -std=c++11 -g test7.cpp编译:

template<typename T>
T id(T x) {return x;}

int main() {
  int i = 0;
  i = i + 1;
} 

在GDB中,我尝试print如下:

Breakpoint 1, main () at test7.cpp:6
6         i = i + 1;
(gdb) print i
$1 = 0
(gdb) print id(i)
No symbol "id" in current context.
(gdb) print id<int>(i)
No symbol "id<int>" in current context.

如您所见,我总是得到“No symbol id”。

有一篇关于GDB not allowing stepping into template functions in OSX的相关帖子。在那里的答案中,模板函数至少可以是disassembled。就我而言,即使disassemble 什么也没提供:

(gdb) disassemble id<int>
No symbol "id<int>" in current context.

是否可以评估模板函数?

附:我正在使用来自 TDM-GCC (4.8.1-2) 的 GDB 7.6.1。

谢谢。

【问题讨论】:

  • 尝试显式实例化函数模板,在main()之前写template int id&lt;int&gt;(int);Read about syntax.
  • 我试过template int id&lt;int&gt;(int);,还是一样的错误。同样一般来说,我们如何实例化可变参数模板函数?

标签: c++ templates gdb


【解决方案1】:

如果源代码中没有显式实例,编译器会将模板代码视为“静态内联”代码,并在未使用时对其进行优化。一个显式实例将创建一个带有外部链接的符号(尽管它仍然可以通过链接器在技术上进行优化,但在我的测试中它没有......):

template<typename T>
T id(T x) {return x;}

template int id<int> (int x);

int main() {
  int i = 0;
  i = i + 1;
} 

gdb 中,我将要调用的 C++ 函数放在单引号内:

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>(int)'(i)
$2 = 0
(gdb)

您在评论中关于创建可变参数模板的显式实例的问题,语法是相同的。您必须为计划调用模板的每个不同参数列表创建不同的显式实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 2021-02-12
    • 1970-01-01
    相关资源
    最近更新 更多