Search code examples
cgccoptimizationpragma

How to change optimization level of one function?


This is related to Determine cause of segfault when using -O3? In the question, I'm catching a segfault in a particular function when compiled with -O3 using a particular version of GCC. At -O3, vectorization instructions are used (at -O2, they are not used).

I want to wrap a single function in a lower optimization level. According to Switching off optimization for a specific function in GCC 4.2.2, I can do it. However, following the various links in the question and answers, I don't find an answer for "how, exactly, to do it".

How do I mark a single function to use a different optimization level?


Related, I don't want to move this function to a separate file, and then provide a different makefile recipe for it. Doing that opens another can of worms, like applying it to GCC 4.9 only on some platforms.


Solution

  • It's described in https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes

    You can change the level by declaring the function like this:

    void some_func() __attribute__ ((optimize(1))) {
        ....
    }
    

    To force optimization level 1 for it.