xref: /llvm-project/clang-tools-extra/docs/clang-tidy/checks/misc/definitions-in-headers.rst (revision cc38cd856d9a9df77d5d727377e38a891807774b)
1.. title:: clang-tidy - misc-definitions-in-headers
2
3misc-definitions-in-headers
4===========================
5
6Finds non-extern non-inline function and variable definitions in header files,
7which can lead to potential ODR violations in case these headers are included
8from multiple translation units.
9
10.. code-block:: c++
11
12   // Foo.h
13   int a = 1; // Warning: variable definition.
14   extern int d; // OK: extern variable.
15
16   namespace N {
17     int e = 2; // Warning: variable definition.
18   }
19
20   // Warning: variable definition.
21   const char* str = "foo";
22
23   // OK: internal linkage variable definitions are ignored for now.
24   // Although these might also cause ODR violations, we can be less certain and
25   // should try to keep the false-positive rate down.
26   static int b = 1;
27   const int c = 1;
28   const char* const str2 = "foo";
29   constexpr int k = 1;
30   namespace { int x = 1; }
31
32   // Warning: function definition.
33   int g() {
34     return 1;
35   }
36
37   // OK: inline function definition is allowed to be defined multiple times.
38   inline int e() {
39     return 1;
40   }
41
42   class A {
43   public:
44     int f1() { return 1; } // OK: implicitly inline member function definition is allowed.
45     int f2();
46
47     static int d;
48   };
49
50   // Warning: not an inline member function definition.
51   int A::f2() { return 1; }
52
53   // OK: class static data member declaration is allowed.
54   int A::d = 1;
55
56   // OK: function template is allowed.
57   template<typename T>
58   T f3() {
59     T a = 1;
60     return a;
61   }
62
63   // Warning: full specialization of a function template is not allowed.
64   template <>
65   int f3() {
66     int a = 1;
67     return a;
68   }
69
70   template <typename T>
71   struct B {
72     void f1();
73   };
74
75   // OK: member function definition of a class template is allowed.
76   template <typename T>
77   void B<T>::f1() {}
78
79   class CE {
80     constexpr static int i = 5; // OK: inline variable definition.
81   };
82
83   inline int i = 5; // OK: inline variable definition.
84
85   constexpr int f10() { return 0; } // OK: constexpr function implies inline.
86
87   // OK: C++14 variable templates are inline.
88   template <class T>
89   constexpr T pi = T(3.1415926L);
90
91When :program:`clang-tidy` is invoked with the `--fix-notes` option, this check
92provides fixes that automatically add the ``inline`` keyword to discovered
93functions. Please note that the addition of the ``inline`` keyword to variables
94is not currently supported by this check.
95