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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9123676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:19:10  来源:igfitidea点击:

How do I view the value of an <optimized out> variable in C++?

c++gdbg++

提问by dangerChihuahua007

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

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

I have this code:

我有这个代码:

int x = floor(sqrt(3));

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?

我想查看 x 的值。但是,gdb 声称 x 是“<optimized_out>”。如何查看 x 的值?我应该更改编译器标志吗?

回答by bdonlan

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

在高优化级别,编译器可以消除中间值,如您在此处所见。有多种选择:

  • You can reduce the optimization level to make it easier for the debugger to keep track of things. -O0is certain to work (but will be quite a lot slower), -O1might 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.
  • 您可以降低优化级别,以便调试器更轻松地跟踪事物。-O0肯定可以工作(但会慢很多),-O1也可以正常工作。
  • 您可以添加一些显式打印语句来记录输出值。
  • 您通常还可以通过将其设置为 volatile 来强制编译器保留此特定值(但请记住在完成后将其取消设置为 volatile!)。但是请注意,由于优化代码中的控制流也会发生变化,即使您可以看到变量的值,当您查看代码时,可能并不完全清楚您所在的代码点有问题的变量。

回答by Gigi

If you can't or don't want to disable optimization, then you can try declaring the variable as volatile. This is usually enough to make your compiler preserve the variable in the final code.

如果您不能或不想禁用优化,那么您可以尝试将该变量声明为 volatile。这通常足以让您的编译器在最终代码中保留变量。

Alternatively, in recent GCC versions you can disable optimization for just a function, like this:

或者,在最近的 GCC 版本中,您可以仅对一个函数禁用优化,如下所示:

void my_function() __attribute__((optimize(0)))
{
  int x = floor(sqrt(3));
}

回答by Gautham Krishnan

Create your own 'global variable' and print the optimized out variable into this global variable. Make sure to remove these globals created by you after you are done with the debugging!

创建您自己的“全局变量”并将优化的输出变量打印到此全局变量中。完成调试后,请确保删除这些由您创建的全局变量!