Disable compiler optimization for function or block of code?

134 views Asked by At

I want to disable compiler optimization for a single function or block of code. I'm in Visual studio 2019 Environment.

I try below:

__forceinline void InsertJunkCode() {

#pragma optimize("", off)

    .... Junk Code ....

#pragma optimize("", on)

}

...

int main() {

    ...

    InsertJunkCode();

    ...

}
...
Error: C2156   pragma must be outside function
...

Is there a way to disable optimization for a single function or block of code?

1

There are 1 answers

0
Clifford On

The optimise pragma works on whole functions only, not arbitrary code segments. As such the pragma must appear outside of any function and applies to all functions defined between the on and the off.

#pragma optimize("", off)
__forceinline void InsertJunkCode() 
{
    .... Junk Code ....
}
#pragma optimize("", on)

This is clear from the documentation:

The optimize pragma must appear outside a function. It takes effect at the first function defined after the pragma is seen.