为什么一个C / C ++程序往往已经优化调试模式下关闭? [英] Why does a C/C++ program often have optimization turned off in debug mode?

查看:128
本文介绍了为什么一个C / C ++程序往往已经优化调试模式下关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在大多数C或C ++环境下,有一个调试模式和释放模式汇编。

纵观两者之间的区别,您会发现调试模式增加了调试符号(通常在大量的编译器的-g选项),但它还会禁用最优化。

在放模式下,你通常有优化的各种开启。

为什么会不同?

In most C or C++ environments, there is a "debug" mode and a "release" mode compilation.
Looking at the difference between the two, you find that the debug mode adds the debug symbols (often the -g option on lots of compilers) but it also disables most optimizations.
In "release" mode, you usually have all sorts of optimizations turned on.
Why the difference?

推荐答案

如果没有,则流程任何优化是线性的。如果你是在5号线和单步,你一步排队6.优化上,你可以得到的指令重新排序,循环展开和各种优化。结果
例如:

Without any optimization on, the flow through your code is linear. If you are on line 5 and single step, you step to line 6. With optimization on, you can get instruction re-ordering, loop unrolling and all sorts of optimizations.
For example:


void foo() {
1:  int i;
2:  for(i = 0; i < 2; )
3:    i++;
4:  return;

在这个例子中,没有优化,可以通过code单一步骤和命中行1,2,3,2,3,2,4

In this example, without optimization, you could single step through the code and hit lines 1, 2, 3, 2, 3, 2, 4

使用时,你可能会得到看起来像一个执行路径优化:2,3,3,4,甚至只是4! (函数什么也不做毕竟...)

With optimization on, you might get an execution path that looks like: 2, 3, 3, 4 or even just 4! (The function does nothing after all...)

底线,调试code。与优化启用可以是一个皇家疼痛!特别是如果你有大量的功能。

Bottom line, debugging code with optimization enabled can be a royal pain! Especially if you have large functions.

请注意,打开优化改变了code!在某些环境(安全关键系统),这是不可接受的和code正在调试必须要在code发货。总得在这种情况下,与优化调试。

Note that turning on optimization changes the code! In certain environment (safety critical systems), this is unacceptable and the code being debugged has to be the code shipped. Gotta debug with optimization on in that case.

虽然优化和非优化code应为功能等价,在某些情况下,该行为将发生变化。结果,
下面是一个简单的例子:结果

While the optimized and non-optimized code should be "functionally" equivalent, under certain circumstances, the behavior will change.
Here is a simplistic example:


    int* ptr = 0xdeadbeef;  // some address to memory-mapped I/O device
    *ptr = 0;   // setup hardware device
    while(*ptr == 1) {    // loop until hardware device is done
       // do something
    }

通过优化功能,这很简单,你还挺知道会发生什么。
但是,如果你打开​​的优化上,一对夫妇的事情可能会发生:

With optimization off, this is straightforward, and you kinda know what to expect. However, if you turn optimization on, a couple of things might happen:


  • 编译器可能会优化,同时街区之遥(我们初始化为0,它永远不会是1)

  • 而不是访问内存,指针访问可能被移动到一个登记册>没有I / O更新

  • 内存访问可能会被缓存的(不一定是编译器优化相关)

在所有这些情况下,该行为是完全不同,最有可能是错误的。

In all these cases, the behavior would be drastically different and most likely wrong.

这篇关于为什么一个C / C ++程序往往已经优化调试模式下关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆