CPP-40 Make it clear that not using #pragma once is almost a stylistic choice

This commit is contained in:
Loïc Joly 2022-07-29 16:24:19 +02:00 committed by GitHub
parent 88797ed932
commit aa5a68be02
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 5 additions and 16 deletions

View File

@ -17,7 +17,7 @@
]
},
"defaultSeverity": "Blocker",
"defaultSeverity": "Minor",
"ruleSpecification": "RSPEC-1852",
"sqKey": "S1852",
"scope": "Main",

View File

@ -1,10 +1,10 @@
``++#pragma once++`` is a preprocessor directive meant to ensure that a file is only included once in a compilation unit. However, there are several reasons to avoid it:
* While it is widely implemented, it's not universally supported.
* It's not part of the standard, so its behavior may vary from compiler to compiler.
* If the same file exists in two different locations, it will _not_ prevent the second file from being included in the compilation.
* It is not part of the standard, which prevents its use in some contexts.
* Even if it is supported by virtually all compilers, since its behavior is not defined, it may differ between compilers, especially for some corner cases when determining if two files are identical (for instance, in the presence of symbolic links).
* Its semantic is slightly different from the semantic of an include guard. For instance, if a file is duplicated in two different locations, `#pragma once` will not prevent multiple inclusion of this file.
For these reasons, include guards, or include guards along with ``++#pragma once++`` should be used instead.
Note: There used to be a build performance improvement when using `#pragma once` instead of an include guard because naive implementations of include guards need to parse the full file to get the `#endif` matching the `#if`. But most modern compilers specifically detect the include guard pattern and use a dedicated optimization that makes it about as fast as `#pragma once`.
== Noncompliant Code Example
@ -27,17 +27,6 @@ For these reasons, include guards, or include guards along with ``++#pragma once
...
#endif
----
or
[source,cpp]
----
// my_header.h
#pragma once
#ifndef MY_HEADER
#define MY_HEADER
...
#endif
----
ifdef::env-github,rspecator-view[]