开发者

What's wrong if compiler optimization is turned on in debug build?

开发者 https://www.devze.com 2023-02-06 00:03 出处:网络
Why is it necessary/recommended to turn off all compiler optimizations when debugging application? Background

Why is it necessary/recommended to turn off all compiler optimizations when debugging application?

Background

I'm working in an 8-bit micro controller (OKI 411) which has 15K usable code memory s开发者_运维问答pace for interrupt service routines + ROM region/window (const global variables) + code. We nearly eat up ~13K so it is very tempting to turn on maximum possible optimization during even debugging.


When compiling a debug binary, the compiler tries to maintain a 1:1 correspondence between code statements (or pieces of code statements) to assembly language instructions. This way, when you are debugging, you can step through, instruction by instruction, and it is easy for the debugger to correlate its current position in the binary with the correct source code. Usually the compiler also ensures that all named variables actually exist somewhere in memory so that you can view their contents in the debugger.

Compiler optimizations may elide unused or unnecessary local variables and may restructure your code so that it is more efficient. Functions may be inlined and expressions may be partially or wholly precomputed or rearranged. Most of these and similar optimizations make it difficult to correlate the original source code with the generated assembly.


Consider:

for (i = 0; i < 10; i++) {
    src[i] = dest[i];
}

After optimization, this code might look like:

src[0] = dest[0];
src[1] = dest[1];
⋮
src[9] = dest[9];

In other words, there's no i anymore. The debugger would expect i to be on the stack frame, but the optimizer removed it.

Also, when stepping, the PC will jump all over the place (apparently randomly), and you will encounter various other weirdness that will make debugging very difficult or impossible (depending on what the optimizer did).


It's fine to turn it on. It's usually off because it makes compiles go faster, which for large projects can be a real concern. It's actually better to turn it on if you can, so that you don't run into any nasty problems due to the optimization at the last minute.

In your case I'd certainly turn it on.

This may cause problems with certain forms of debugging, but you should be able to flip it off in those cases.


I came across a similar situation where I was trying to read from a hardware register,the register was a memory-mapped,and it gave me wrong values with CFLAGS="-o2" in gcc.However when i turned CFLAGS="-O0",it started working.It may be worth mentioning that the same result can be achieved by casting it to a volatile variable so the compiler optimization is bypassed.


The only thing I can think of is that it might make debugging more difficult.

Other than that, there should be no problems.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号