karthik
karthik

Reputation: 17842

Which is efficient to use #pragma once or #ifndef #endif?

To avoid multiple includes of a header file, one of my friend suggested the following way

  #ifndef _INTERFACEMESSAGE_HPP
  #define _INTERFACEMESSAGE_HPP
  class CInterfaceMessage
  {
     / /Declaration of class goes here
  //i.e declaration of member variables and methods 
   private:
   int m_nCount;
     CString m_cStrMessage;
    public:
    CString foo(int);
 }
   #endif

where _INTERFACEMESSAGE_HPP is just an identifier

but when i declare a class using visual studio 2005 IDE I get a statement as #pragma once at the starting of the class definition when i took the help of msdn to find the purpose of #pragma once it gave me the following explanation

"Specifies that the file will be included (opened) only once by the compiler when compiling a source code file. "

Someone please tell which is the right approach?, if both are correct then what is the difference? is one approach is better than the other?

Upvotes: 6

Views: 3693

Answers (3)

Arc
Arc

Reputation: 11296

Pragmas are compiler-specific, so I'd use #ifndef.

Preprocessor directives are resolved during (actually, before) compilation, so they do not make a difference in runtime except maybe for compile time.

However, you will never notice a difference in compile time from these two alternatives unless you use them several thousand times I guess.

Upvotes: 4

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174369

The first approach is the generic approach that works with all compilers and is also the older one around. The #pragma once approach is compiler specific.

Upvotes: 2

karthik
karthik

Reputation: 17842

gcc has pragma once as deprecated. You should use the standard include guards. All pragma directives are by definition implementation defined. So, if you want portability, don't use them.

Upvotes: 7

Related Questions