“无法评估函数――可能是内联的"STL 模板容器的 GDB 中的错误

2022-01-20 00:00:00 gdb c++

我希望能够使用 GDB 从 STL 容器中获取地址并打印一对.

I want to be able to get the address and print a single pair from an STL container using GDB.

例如,给定以下玩具程序:

E.g., given the following toy program:

#include <map>

int main() 
{
  std::map<int,int> amap;
  amap.insert(std::make_pair(1,2));

}

我编译为:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp

然后,当我尝试检查地图的单个元素时,例如:

Then, when I try to examine a single element of map, for example:

p amap.begin()

我明白了:

"Cannot evaluate function -- may be in-lined" 

为什么会发生这种情况,我该如何解决?

Why is this happening and how do I work around it?

在 Ubuntu 20.04、GCC 9.3.0、2.34 中测试.

Tested in Ubuntu 20.04, GCC 9.3.0, 2.34.

推荐答案

这是因为生成的二进制文件中不存在 amap.begin().这就是 C++ 模板的工作方式:如果您不使用或显式实例化某些模板方法,则它不会在生成的二进制文件中生成.

This is because amap.begin() does not exist in resulting binary. This is how C++ templates work: if you don't use or explicitly instantiate some template method it is not generated in resulting binary.

如果你想从 gdb 调用 amap.begin() 你必须实例化它.一种方法是实例化 std::map:

If you do want to call amap.begin() from gdb you have to instantiate it. One way to do it is to instantiate all methods of std::map:

#include <map>

template class std::map<int,int>;

int main()
{
  std::map<int,int> amap;
  amap.insert(std::make_pair(1,2));
}

gdb 会话:

(gdb) p amap.begin()
$1 = {first = 1, second = 2}

相关文章