
Co-authored-by: Marco Borgeaud <89914223+marco-antognini-sonarsource@users.noreply.github.com>
55 lines
1.8 KiB
Plaintext
55 lines
1.8 KiB
Plaintext
== Why is this an issue?
|
|
|
|
``++#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:
|
|
|
|
* 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.
|
|
|
|
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
|
|
|
|
[source,cpp]
|
|
----
|
|
// my_header.h
|
|
#pragma once
|
|
...
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,cpp]
|
|
----
|
|
// my_header.h
|
|
#ifndef MY_HEADER
|
|
#define MY_HEADER
|
|
...
|
|
#endif
|
|
----
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Remove this use of "#pragma once" and use include guards instead
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 30 Jul 2014, 20:25:37 Freddy Mallet wrote:
|
|
If my feeling is correct :
|
|
|
|
* The purpose of this rule is mainly to prevent a portability issue from one compiler to another or from one version of the language to another. So I would use the "Portability" category.
|
|
|
|
endif::env-github,rspecator-view[]
|