使用 #pragma Once 或 #ifndef #endif 哪个更有效?

发布于 2024-10-30 09:07:20 字数 594 浏览 0 评论 0原文

为了避免多次包含头文件,我的一位朋友建议采用以下方法

  #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

,其中 _INTERFACEMESSAGE_HPP 只是一个标识符,

但是当我使用 Visual Studio 2005 IDE 声明一个类时,我得到一条语句: #pragma 一次 在类定义的开头 当我在msdn的帮助下找到#pragma的目的时 它给了我以下解释

“指定编译器在编译源代码文件时仅包含(打开)该文件一次。”

有人请告诉我哪种方法是正确的?如果两者都正确,那么有什么区别?一种方法比另一种更好吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

呆橘 2024-11-06 09:07:20

gcc 有一次 pragma 已弃用。您应该使用标准包含防护。所有编译指令都是根据定义实现来定义的。因此,如果您想要便携性,请不要使用它们。

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.

乱世争霸 2024-11-06 09:07:20

编译指示是特定于编译器的,因此我会使用#ifndef。

预处理器指令在编译期间(实际上是在编译之前)解析,因此除了编译时之外,它们在运行时不会产生任何影响。

然而,我猜你永远不会注意到这两种替代方案在编译时间上的差异,除非你使用它们几千次。

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.

靑春怀旧 2024-11-06 09:07:20

第一种方法是适用于所有编译器的通用方法,也是较旧的方法。 #pragma Once 方法是特定于编译器的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文