How to prevent compiler from optimizing away breakpoint?

試著忘記壹切 提交于 2019-12-24 01:19:21

问题


I have written an if-clause that checks whether I should break the program for debugging or not:

if (a < 0) {
    a = a;
}

a should not become negative, but I have found that it does, and I want to break for debugging to see why it becomes negative if that happens, hence I have written this if-clause. On the line a = a; I have set a breakpoint, which is supposed to stop the program if it enters the if-clause. The thing is that the line doesn't do anything (which is necessary in order not to mess anything up), so the line is optimized away and the breakpoint ends up after the if-clause. This trick usually works but apparently the compiler wasn't very found of it this time.

The language is C++, and I'm compiling with qmake (a Qt tool) and mingw.

My question is, how can I prevent the compiler from optimizing away lines of code when I have breakpoints set on them? Or is there some other way to conditionally break the program for debugging?


回答1:


One possibility is to call an I/O function. In Java, one could write:

if (a < 0) {
    System.out.printf("");
}

Similarly, in C/C++, one could write:

if (a < 0) {
    printf("");
}

Even though the function call is effectively a no-op, the compiler doesn't know that, and is unlikely to optimize the call away.

Or is there some other way to conditionally break the program for debugging?

Many modern IDE allow one to set conditional breakpoints: Visual Studio, Eclipse.




回答2:


I usually put a printf (or cout, or whatever is appropriate for the language that you are using) here so that I can set a breakpoint, e.g.

if (a < 0) {
    printf("a < 0 !\n"); // <<< set breakpoint here
}



回答3:


If it's C or C++, simply defining a as volatile should help.




回答4:


I defined a NO_OP() macro which doesn't do anything and doesn't require the file that's using it to include any header files:

#define  NO_OP()  {float f = 0; if (f != 0) exit(0);}

I don't know if the compiler will be able to optimize this macro away, but it works for me with MinGW.




回答5:


It’s not portable, but with MSVC I use __asm nop (surrounded by #ifndef NDEBUG#endif if the code is likely to remain in place for a while) to insert a literal no-op that I know the compiler won’t touch.



来源:https://stackoverflow.com/questions/10518204/how-to-prevent-compiler-from-optimizing-away-breakpoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!