| 1 |
.. title:: clang-tidy - misc-use-anonymous-namespace |
| 2 |
|
| 3 |
misc-use-anonymous-namespace |
| 4 |
============================ |
| 5 |
|
| 6 |
Finds instances of ``static`` functions or variables declared at global scope |
| 7 |
that could instead be moved into an anonymous namespace. |
| 8 |
|
| 9 |
Anonymous namespaces are the "superior alternative" according to the C++ |
| 10 |
Standard. ``static`` was proposed for deprecation, but later un-deprecated to |
| 11 |
keep C compatibility [1]. ``static`` is an overloaded term with different meanings in |
| 12 |
different contexts, so it can create confusion. |
| 13 |
|
| 14 |
The following uses of ``static`` will *not* be diagnosed: |
| 15 |
|
| 16 |
* Functions or variables in header files, since anonymous namespaces in headers |
| 17 |
is considered an antipattern. Allowed header file extensions can be configured |
| 18 |
via the `HeaderFileExtensions` option (see below). |
| 19 |
* ``const`` or ``constexpr`` variables, since they already have implicit internal |
| 20 |
linkage in C++. |
| 21 |
|
| 22 |
Examples: |
| 23 |
|
| 24 |
.. code-block:: c++ |
| 25 |
|
| 26 |
// Bad |
| 27 |
static void foo(); |
| 28 |
static int x; |
| 29 |
|
| 30 |
// Good |
| 31 |
namespace { |
| 32 |
void foo(); |
| 33 |
int x; |
| 34 |
} // namespace |
| 35 |
|
| 36 |
Options |
| 37 |
------- |
| 38 |
|
| 39 |
.. option:: HeaderFileExtensions |
| 40 |
|
| 41 |
A semicolon-separated list of filename extensions of header files (the filename |
| 42 |
extensions should not include "." prefix). Default is ";h;hh;hpp;hxx". |
| 43 |
For extension-less header files, using an empty string or leaving an |
| 44 |
empty string between ";" if there are other filename extensions. |
| 45 |
|
| 46 |
[1] `Undeprecating static <https://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1012>`_ |