| 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 global option `HeaderFileExtensions`. |
| 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 |
[1] `Undeprecating static <https://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1012>`_ |