简体   繁体   English

以优化的代码行停止调试器

[英]Stopping debugger at an optimized out line of code

If I want to stop in an empty block of code it's always a problem. 如果我想停在一个空的代码块中,那总是一个问题。

if (...)
{ // I want the debugger to stop here!
}

If I add an arbitrary line of code which does not affect program behaviour it is likely to be optimized out, depending on the line 如果我添加任意一行代码,这些代码不影响程序行为,则可能会根据代码行对其进行优化

if (...)
{ 
   int a;
   a = a; // won't work
}
if (...)
{ 
   int a;
   int b = a; // will work
}

So the 2 questions arise here: 因此,这里出现两个问题:

1) What is the simplest one-line code which will NOT be optimized out (but will really do nothing!), which I can use to stop the debugger? 1)什么最简单的单行代码不会被优化(但实际上什么也做不了!),可以用来停止调试器? 2) Is there a way to switch all of optimizations so that to be able to stop at an arbitrary line of code? 2)有没有办法切换所有优化,以便能够停在任意代码行? Compiler flag -O0 doesn't work. 编译器标志-O0不起作用。

A good enough one-line code could be some useful and interesting assert statement with a condition which would not be constant-folded by the compiler. 足够好的单行代码可能是一些有用且有趣的assert语句,但条件是编译器无法将其固定折叠。 Often some meaningful and useful assert (p!=NULL) or assert(i>0) where p is some existing pointer variable or formal, or i is some existing signed integer variable or formal, is enough. 通常,一些有意义且有用的assert (p!=NULL)assert(i>0)足够了,其中p是一些现有的指针变量或形式,或者i是一些现有的带符号整数变量或形式。

BTW, you are in the debugging phase of your project, so adding good enough meaningful assert statements is helpful. 顺便说一句,您处于项目的调试阶段,因此添加足够好的有意义的assert语句将很有帮助。 Of course you want the <cassert> header to be included. 当然,您希望包含<cassert>标头。

Don't forget that assert(3) statements are skipped if you compile with the -DNDEBUG flag. 不要忘记,如果使用-DNDEBUG标志进行编译,则会跳过assert(3)语句。

You could also use (on Linux/x86) asm volatile ("nop") . 您也可以在Linux / x86上使用asm volatile ("nop") Notice that the debugger needs some code to put a breakpoint at. 注意,调试器需要一些代码来放置断点。 You don't want an empty code. 您不需要代码。

What about using a static breakpoint ? 使用静态断点呢?

#include <sys/sdt.h>

if (condition)
  DTRACE_PROBE(myapp, foo);

Now you can set a breakpoint in GDB: 现在,您可以在GDB中设置一个断点

break -probe-stap myapp:foo

You can even use: 您甚至可以使用:

DTRACE_PROBE1(myapp, foo, condition);

with: 有:

break -probe-stap myapp:foo if $_probe_arg0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM