如何在 gdb 中“打印"/评估 C++ 模板函数
我想知道是否可以使用 gdb print
命令来评估 c++ 模板函数的结果.在下面带有简单 id
函数的代码中,我尝试 print
id(x)
的结果,但它好像 id
或 id<t>
从未存在过.我使用的代码如下,用 g++ -std=c++11 -g test7.cpp
编译:
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
function, I tried to print
results of id(x)
, but it's as if id
or id<t>
never existed. The code I use is below, compiled with 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
如下:
In GDB, I tried to print
as follows:
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".
As you can see, I always get "No symbol id".
有一篇关于GDB的相关帖子不允许进入 OSX 中的模板函数.在那里的答案中,模板函数至少可以是 disassemble
d.在我的情况下,即使 disassemble
什么也没提供:
There is a related post about GDB not allowing stepping into template functions in OSX. In the answers there, the template function can at least be disassemble
d. In my case, even disassemble
gives nothing:
(gdb) disassemble id<int>
No symbol "id<int>" in current context.
是否可以评估模板函数?
Is it possible to evaluate template functions at all?
附:我正在使用来自 TDM-GCC (4.8.1-2) 的 GDB 7.6.1.
P.S. I am using GDB 7.6.1 coming from TDM-GCC (4.8.1-2).
谢谢.
推荐答案
如果源代码中没有显式实例,编译器会将模板代码视为静态内联"代码,并在未使用时对其进行优化.一个显式实例将创建一个带有外部链接的符号(尽管它仍然可以通过链接器在技术上进行优化,但在我的测试中它没有......):
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<typename T>
T id(T x) {return x;}
template int id<int> (int x);
int main() {
int i = 0;
i = i + 1;
}
在 gdb
中,我将要调用的 C++ 函数放在单引号内:
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>(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.
相关文章