Unexpected Error: "Undefined Reference to Static constexpr char[]" in Class Definition
Encountering an "Undefined Reference to Static constexpr char[]" error while defining a static const char array within a class can be perplexing. Let's delve into the issue and explore the solution.
As highlighted in the error message, the compiler expects a definition for the static member. In the provided code snippet, you've included the declaration and initializer within the class definition, but you haven't provided the separate definition in the .cpp file.
To resolve this, follow these steps:
In the .cpp file, add the definition by declaring the static member without the initializer, as seen below:
constexpr char foo::baz[];
Maintain the class declaration and initializer for the static member in the .hpp file as it is.
Explanation:
In C , static members are allocated memory during compilation and shared across all instances of the class. When defining a static const char array, both the declaration and the initializer must be included in the header file (.hpp). However, the definition (without the initializer) must be provided separately in the implementation file (.cpp) to resolve the linkage issue. This ensures that the definition for the static member is accessible during linking, resolving the "Undefined Reference" error.
The above is the detailed content of Why Do I Get an 'Undefined Reference to Static constexpr char[]' Error in C ?. For more information, please follow other related articles on the PHP Chinese website!