3

Very frequently, I want to test the value of a variable in a function via a breakpoint. In many cases, that variable never actually gets referenced by any code that "does stuff", but that doesn't mean I don't still want to see it. Unfortunately, the optimizer is working against me and simply removing all such code when compiling, so I have to come up with convoluted grossness to fool the compiler into thinking those values actually matter so they don't get optimized away. I don't want to turn the optimizer off, as it's doing important stuff in other places, but just for this one block of code I'd like to temporarily disable it for the sake of debugging.

4

6 回答 6

4

产生可观察行为的代码符合定义的要求。例如,printf("")

对 volatile 变量的访问也正式构成了可观察的行为,尽管如果某些编译器仍然丢弃“不必要的” volatile 变量,我不会感到惊讶。

出于这个原因,对我来说,调用 I/O 函数似乎是最好的选择。

于 2012-07-28T00:00:16.840 回答
1

您可以尝试“volatile”关键字。一些介绍位于http://en.wikipedia.org/wiki/Volatile_variable

一般来说, volatile 关键字旨在防止编译器对假定变量值不能“自行”更改的代码进行任何优化。

于 2012-07-27T23:59:53.827 回答
0

你没有指定你的编译器,所以我将在这里添加我一直在对我专门用于调试的任何变量使用 volatile 说明符。在我的编译器(Embarcadero RAD Studio C++ Builder)中,我已经使用它几年了,并且没有一次对变量进行过优化。也许你不使用这个编译器,但如果你这样做了,我可以说 volatile 肯定一直对我有用。

于 2012-07-28T00:07:33.163 回答
0

这是我使用的技巧的一个示例:

#include <ctime>
#include <iostream>
int main() {
    std::cout << "before\n";
    if (std::time(NULL) == 0) {
        std::cout << "This should not appear\n";
    }
    std::cout << "after\n";
}

time()调用应始终返回一个正值,但编译器无法知道这一点。

于 2012-07-28T00:26:47.387 回答
0

如果变量的唯一目的是在使用调试器的断点中查看变量,则可以将变量设为全局变量。例如,您可以维护一个全局缓冲区:

#ifdef DEBUG
char dbg_buffer[512];
template <typename T>
void poke_dbg (const T &t) {
    memcpy(dbg_buffer, &t, sizeof(T));
}
#else
#define poke_dbg(x)
#endif

然后在调试期间,您可以检查 dbg_buffer 的内容(如果需要,可以使用适当的强制转换)。

于 2012-07-28T02:08:05.823 回答
0

你有没有尝试过

#pragma optimize("",off)

?

我认为特定于 MSVS - http://msdn.microsoft.com/en-us/library/chh3fb0k(v=vs.80).aspx

于 2012-07-27T23:56:01.447 回答