C++ - How to use #pragma once

The #pragma once compiler directive guarantees that a header file will be processed only once per translation unit.
This can result in a significant reduction in compile time.

#pragma once


  // myclass.h
  
  #pragma once
  
  class MyClass {
      // ...
  };
  

Non-standard. Originally Microsoft only.

include guards


  // myclass.h
  
  #ifndef _INC_CMYCLASS_H_
  #define _INC_CMYCLASS_H_
  
  class MyClass {
      // ...
  };
  
  #endif
  

Tried and tested. Portable.

Both


  // myclass.h
  
  #pragma once
  #ifndef _INC_CMYCLASS_H_
  #define _INC_CMYCLASS_H_
  
  class MyClass {
      // ...
  };
  
  #endif
  

Not recommended. Pick one or the other.
This introduces additional complexity with no benefit.

Ads by Google

Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath