Is #pragma once part of the C++11 standard?

前端 未结 2 728
野的像风
野的像风 2020-11-28 22:53

Traditionally, the standard and portable way to avoid multiple header inclusions in C++ was/is to use the #ifndef - #define - #endifpre-compiler directives sch

相关标签:
2条回答
  • 2020-11-28 23:24

    Section §16.6 of the Standard (N3936 draft) describes #pragma directives as:

    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.

    Basically #pragma once is an implementation specific instance of a #pragma directive, and no, it's not standard. Yet.

    It is often widely supported by most "major compilers" including GCC and Clang and is therefore sometimes recommended to avoid include-guards boilerplate.

    0 讨论(0)
  • 2020-11-28 23:32

    #pragma once is not standard. It is a widespread (but not universal) extension, which can be used

    • if your portability concerns are limited, and
    • you can be sure that all of your include files are always on a local disk.

    It was considered for standardization, but rejected because it cannot be implemented reliably. (The problems occur when you have files accessible through several different remote mounts.)

    It's fairly easy to ensure that there are no include guard conflicts within a single development. For libraries, which may be used by many different developments, the obvious solution is to generate a lot of random characters for the include guard when you create it. (A good editor can be set up to do this for you whenever you open a new header.) But even without this, I've yet to encounter any problems with conflicts between libraries.

    0 讨论(0)
提交回复
热议问题