Undefined Reference to Static constexpr Char Array: Understanding the Undefined Reference Issue
In the C programming language, it is possible to define static constant character arrays within a class. However, developers may encounter an "undefined reference" error when attempting to reference such arrays in their code. This error occurs because the compiler requires both a declaration and a definition of the static member.
To resolve this issue, the code should be modified as follows. In the class definition (.hpp file), the declaration and initialization of the static array should remain inside the class. In the implementation file (.cpp file), a separate line should be added to provide the definition of the static array.
// .hpp struct foo { void bar(); static constexpr char baz[] = "quz"; }; // .cpp void foo::bar() { std::string str(baz); // now compiles successfully } constexpr char foo::baz[]; // definition of static member
By providing the definition of the static member separately, the compiler can link the reference to the array correctly, resolving the undefined reference error. This separation between declaration and definition is necessary because the array's size must be known during compilation, while its initialization can be deferred until later.
The above is the detailed content of Why Do I Get an 'Undefined Reference' Error with Static constexpr Char Arrays in C ?. For more information, please follow other related articles on the PHP Chinese website!