Home > Backend Development > C++ > Why Do I Get a Linker Error When Defining Static Const Integer Members in a C Class?

Why Do I Get a Linker Error When Defining Static Const Integer Members in a C Class?

Linda Hamilton
Release: 2024-12-01 13:14:09
Original
277 people have browsed it

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 << test::N << "\n";
    std::min(9, test::N);
}
Copy after login

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.

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):

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.

To resolve the linker error, one can define the static const member outside the class, typically in the corresponding source file:

const int test::N = 10;
Copy after login

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;
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template