Static Const Integer Members and the Undefined Reference Error
The C language permits the definition of static const members within a class definition for integer types. However, a recent attempt at this has encountered a linker error. Specifically, a class named "test" declared a static const integer member "N" with a value of 10. When attempting to access and use "N" in a subsequent function, the code fails with an undefined reference error.
Integer-Type Constant Initialization
While the class declaration allows for an initial value to be set for "N," it should be noted that this is merely an initializer, not a complete definition. According to the C standard, static const integral members require a definition outside the class declaration.
Impact of Reference Parameters
The culprit in this case is the call to the "std::min" function. As "std::min" takes its parameters by constant reference, it requires that "N" be fully defined. The absence of a separate definition for "N" leads to the undefined reference error.
Avoiding the Error
To resolve the issue, a definition of "N" must be provided outside of the class declaration. This can be achieved by declaring and initializing "N" in a separate namespace or header file. Additionally, it may be beneficial to use the "constexpr" keyword to ensure that "N" is evaluated at compile-time.
Conclusion
The linker error encountered in this instance stems from the incomplete definition of the static const integer member "N." By understanding the distinction between initialization and definition and addressing the needs of reference parameters, this issue can be effectively rectified.
The above is the detailed content of Why Does Accessing a Static Const Integer Member Result in an Undefined Reference Error in C ?. For more information, please follow other related articles on the PHP Chinese website!