Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. -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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...