0

Should #pragma optimize reside in B.h,

class B{
    #pragma optimize( "", off )
    public: void f();
    #pragma optimize( "", on )
};

or B.cpp

#include "B.h"
#pragma optimize( "", off )
void B::f(){

}
#pragma optimize( "", on )

or both?

There is a useful description from the official site ( https://learn.microsoft.com/en-us/cpp/preprocessor/optimize?view=vs-2019 ), but I am not sure what it means:

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

What does the "defined" mean - declaration or implementation?

Similar questions / references

yacc
  • 2,915
  • 4
  • 19
  • 33
cppBeginner
  • 1,114
  • 9
  • 27
  • What you call the implementation is also known as the definition. – eesiraed Jun 05 '19 at 03:39
  • @Alexander Zhang Thank, I agree. I tried to add in `.cpp`, but it didn't work. Thus, I guessed I misunderstand somethings. Hmm... – cppBeginner Jun 05 '19 at 03:44
  • To make portable code, pragmas should be prevented in general. (I admit this might be a matter of personal preference. Portable code might not be required.) However, the need of explicit controling how the compiler optimizes code appears a bit questionable to me. (I would like to know why this should be necessary. For clean code, it shouldn't.) Hence, I was quite happy to read the linked answer [SO: Why #pragma optimize(“”, off)](https://stackoverflow.com/a/29033590/7478597) (which I understand that my feelings about this are not that bad). – Scheff's Cat Jun 05 '19 at 05:38
  • @Scheff Is it possible to encapsulate it into some macro (to make it portable)? I just want to use it for debugging. – cppBeginner Jun 05 '19 at 05:39
  • The class declaration in header produces just an "interface". Actual code is produced for the implementation (aka definition) i.e. `B::f() { }` (in `B.cpp`). Without deeper knowledge I would guess that `#pragma`s are needed around the latter. – Scheff's Cat Jun 05 '19 at 05:41
  • You may fiddle this out comparing (amount of) produced code for a small example on [Compiler Explorer](https://www.godbolt.org) (with vs. without the `#pragma`s). There is support for some of the newest MS VC++ compilers among others. – Scheff's Cat Jun 05 '19 at 05:43
  • Btw. I believe wrongly placed `#pragma`s in the class declaration in header (in this case) just don't have any effect. (There isn't produced binary code which might be subject of (non-)optimization.) To me, it appears like switching the lamp on/off while the plug is not in the wall socket. ;-) – Scheff's Cat Jun 05 '19 at 05:48
  • @Scheff I agree with everything you said. Thank. – cppBeginner Jun 05 '19 at 06:06

0 Answers0