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
567 views
in Technique[技术] by (71.8m points)

c++ - Visual Studio. Debug. How to save to a file all the values a variable has had during the duration of a run?

I am watching a variable that gets assigned thousands of values during a single run. It is being set several times and is hard to keep track of the code workflow just by setting breakpoints where it is being reassigned. Is there a way to output all the values the variable had to a .txt file? I want to achive this without modifying the actual C++ code, just using the debugging tools.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

To get really close to what you're looking for, you need to combine two features of Visual Studio: Data breakpoints and trace points. Data breakpoints allow you to notify the debugger, whenever the store value in memory changes. To set a data breakpoint, launch the debugger, and select DebugNew BreakpointData Breakpoint...:

New Data Breakpoint

Since we are interested in the variable myValue, we're setting the address to &myValue, and set the size to 4 bytes (since that's what an int is on Windows):

Data Breakpoint Settings

Now that would be pretty cool as-is already. But for non-intrusive logging, we'll set the Actions as well:

Data Breakpoint Actions

The important settings are the log message ([MYSIG] is an arbitrary signature, so that the interesting log entries can later be filtered), that dumps the value of the variable, as well as the Continue execution check box. The latter makes this non-intrusive (or low-intrusive; logging lots of information does have a noticeable impact on runtime performance).

With that in place, running this code

inline void DataTracepoint() {
    volatile int myValue{ 0 };
    for ( int i = 0; i < 10; ++i ) {
        myValue = i;
    }
}

produces the following output in the Debug output pane:

[MYSIG] myValue = 0
[MYSIG] myValue = 1
[MYSIG] myValue = 2
[MYSIG] myValue = 3
[MYSIG] myValue = 4
[MYSIG] myValue = 5
[MYSIG] myValue = 6
[MYSIG] myValue = 7
[MYSIG] myValue = 8
[MYSIG] myValue = 9

This output can then be easily analyzed in your favorite text processor.


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

...