xref: /llvm-project/clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst (revision cc38cd856d9a9df77d5d727377e38a891807774b)
1.. title:: clang-tidy - misc-use-anonymous-namespace
2
3misc-use-anonymous-namespace
4============================
5
6Finds instances of ``static`` functions or variables declared at global scope
7that could instead be moved into an anonymous namespace.
8
9Anonymous namespaces are the "superior alternative" according to the C++
10Standard. ``static`` was proposed for deprecation, but later un-deprecated to
11keep C compatibility [1]. ``static`` is an overloaded term with different meanings in
12different contexts, so it can create confusion.
13
14The 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
22Examples:
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>`_
37