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

查看:250
本文介绍了为什么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;

在这个例子中,没有优化,你可以单步执行代码并命中行1, 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...)

底线,调试代码与优化启用可以是皇家的痛苦!特别是如果你有大功能。

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

请注意,打开优化更改代码!在某些环境(安全关键系统)中,这是不可接受的,被调试的代码必须是发运的代码。

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.

虽然优化和非优化代码应该是功能等效的,但在某些情况下,行为会改变。 >
这是一个简单的例子:

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:


  • 编译器可能会优化while块我们初始化为0,它永远不会是1)

  • 指针访问可能被移动到一个寄存器 - >没有I / O更新

  • 内存访问可能已缓存(不一定与编译器优化相关)

在所有这些情况下,很可能是错误的。

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

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

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