When attempting to access a static constexpr character array within a class method, you may encounter an "undefined reference" error. This issue arises when the declaration and initialization of the array occur within the class definition, but the definition itself is omitted.
Problem:
// header file (.hpp) struct foo { void bar(); static constexpr char baz[] = "quz"; // Declaration and initialization }; // implementation file (.cpp) void foo::bar() { std::string str(baz); // "undefined reference to baz" error }
Solution:
To resolve this issue, you must provide a separate definition for the static member in the implementation file (.cpp) in addition to the declaration in the class definition (.hpp):
// implementation file (.cpp) constexpr char foo::baz[]; // Definition
Explanation:
The compiler needs both the declaration and the definition of the static member to know its memory location and its initial value. The declaration in the class definition only specifies the type and name of the member, whereas the definition provides the actual memory allocation and initialization. By separating the definition from the declaration, you ensure that the compiler has all the necessary information to link the member to its definition during compilation.
The above is the detailed content of Why Do I Get an 'Undefined Reference' Error When Using a Static constexpr char Array in a Class Method?. For more information, please follow other related articles on the PHP Chinese website!