如何查看 <optimized out> 的值?C++中的变量?

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

我正在使用 gdb 调试 C++ 程序.

I am using gdb to debug a C++ program.

我有这个代码:

int x = floor(sqrt(3));

我想查看 x 的值.但是,gdb 声称 x 是".如何查看 x 的值?我应该更改我的编译器标志吗?

and I want to view the value of x. However, gdb claims that x is "< optimized_out >". How do I view the value of x? Should I change my compiler flags?

推荐答案

在高优化级别上,编译器可以消除中间值,正如您在此处看到的.有多种选择:

On high optimization levels, the compiler can eliminate intermediate values, as you have seen here. There are a number of options:

  • 您可以降低优化级别,使调试器更容易跟踪事物.-O0 肯定可以工作(但会慢很多),-O1 也可以正常工作.
  • 您可以添加一些显式打印语句来记录输出值.
  • 您通常也可以强制编译器通过将其设置为 volatile 来保留此特定值(但请记住在完成后将其取消设置为 volatile!).但是请注意,由于控制流在优化代码中也会发生变化,即使您可以看到变量的值,当您查看有问题的变量.
  • You can reduce the optimization level to make it easier for the debugger to keep track of things. -O0 is certain to work (but will be quite a lot slower), -O1 might work okay as well.
  • You can add some explicit print statements to log the output value.
  • You can also usually force the compiler to retain this specific value by making it volatile (but remember to un-make it volatile when you're done!). Note, however, that since control flow is also subject to alteration in optimized code, even if you can see the value of the variable, it may not be entirely clear what point in the code you're at when you're looking at the variable in question.

相关文章