c++cportabilitypragma

How portable is code with #pragma optimize?


How portable is code that uses #pragma optimize? Do most compilers support it and how complete is the support for this #pragma?


Solution

  • #pragma is the sanctioned and portable way for compilers to add non-sanctioned and non-portable language extensions *.

    Basically, you never know for sure, and at least one major C++ compiler (g++) does not support this pragma as is.


    *:

    From the C++ standard (N3242):

    16.6 Pragma directive [cpp.pragma]

    A preprocessing directive of the form

    # pragma pp-tokensopt new-line

    causes the implementation to behave in an implementation-defined manner. The behavior might cause translation to fail or cause the translator or the resulting program to behave in a non-conforming manner. Any pragma that is not recognized by the implementation is ignored.

    From the C standard (Committee Draft — April 12, 2011):

    6.10.6 Pragma directive

    Semantics

    A preprocessing directive of the form

    # pragma pp-tokensopt new-line

    where the preprocessing token STDC does not immediately follow pragma in the directive (prior to any macro replacement)174) causes the implementation to behave in an implementation-defined manner. The behavior might cause translation to fail or cause the translator or the resulting program to behave in a non-conforming manner. Any such pragma that is not recognized by the implementation is ignored.

    And here's an example:

    int main () {
        #pragma omp parallel for
        for (int i=0; i<16; ++i) {}
    }
    

    A big part of the C and C++ OpenMP API is implemented as #pragmas.