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
Linda HamiltonOriginal
2024-12-01 13:14:09232browse

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);
}

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;

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!

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