Home >Backend Development >C++ >Why Do I Get a Linker Error When Defining Static Const Integer Members in a C Class?
Linker Error in Defining Static Const Integer Members in Class Definition
Class declarations in C allow for the definition of static const integer members within the class. However, users may encounter linker errors with code similar to the example provided:
class test { public: static const int N = 10; }; int main() { std::cout <p>While the compiler accepts the class definition, the linker reports an undefined reference to test::N. The issue arises because the declaration in the class is not a true definition.</p><p>In C , static const integral members must be defined outside the class in a namespace scope. This is because they cannot be initialized within the class declaration according to the C standard (9.4.2/4):</p><blockquote>If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer [...] In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.</blockquote><p>To resolve the linker error, one can define the static const member outside the class, typically in the corresponding source file:</p><pre class="brush:php;toolbar:false">const int test::N = 10;
Alternatively, for C 11 and later, the constexpr keyword can be used to create a true definition within the class declaration:
class test { public: static constexpr int N = 10; };
The above is the detailed content of Why Do I Get a Linker Error When Defining Static Const Integer Members in a C Class?. For more information, please follow other related articles on the PHP Chinese website!