Why #pragma optimize(“”, off)

前端 未结 4 1251
走了就别回头了
走了就别回头了 2021-02-04 03:16

I\'m reviewing a C++ MFC project. At the beginning of some of the files there is this line:

#pragma optimize(\"\", off)

I get that this turns o

相关标签:
4条回答
  • 2021-02-04 03:25

    I have used this exclusively to get better debug information in a particular set of code with the rest of the application is compiled with the optimization on. This is very useful when running with a full debug build is impossible due to the performance requirement of your application.

    0 讨论(0)
  • 2021-02-04 03:27

    Another alternative reason for these to be in a code base... Its an accident.

    This is a very handy tool for turning off the optimizer on a specific file whilst debugging - as Ray mentioned above.

    If changelists are not reviewed carefully before committing, it is very easy for these lines to make their way into codebases, simply because they were 'accidentally' still there when other changes were committed.

    0 讨论(0)
  • 2021-02-04 03:34

    I know this is an old topic, but I would add that there is another reason to use this directive - though not relevant for most application developers.

    When writing device drivers or other low-level code, the optimizer sometimes produces output that does not interact with the hardware correctly.

    For example code that needs to read a memory-mapped register (but not use the value read) to clear an interrupt might be optimized out by the compiler, producing assembly code that does not work.

    This might also illustrate why (as Angew notes) use of this directive should be clearly documented.

    0 讨论(0)
  • 2021-02-04 03:46

    I've seen production code which is correct but so complicated that it confuses the optimiser into producing incorrect output. This could be the reason to turn optimisations off.

    However, I'd consider it much more likely that the code is simply buggy, having Undefined Behaviour. The optimiser exposes that and leads to incorrect runtime behaviour or crashes. Without optimisations, the code happens to "work." And rather than find and remove the underlying problem, someone "fixed" it by disabling optimisations and leaving it at that.

    Of course, this is about as fragile and workarounds can get. New hardware, new OS patch, new compiler patch, any of these can break such a "fix."

    Even if the pragma is there for the first reason, it should be heavily documented.

    0 讨论(0)
提交回复
热议问题