Home >Backend Development >C++ >Why Does My Static `constexpr char` Array Cause an 'Undefined Reference'?
Undefined Reference to Static constexpr char[]
When attempting to create a static const char array as a member of a class, you may encounter the error "undefined reference to baz."
Explanation:
GCC requires you to use constexpr for static const arrays. However, placing the array declaration and initializer within the class definition alone is not sufficient. You must also provide a separate member definition in the .cpp file.
To resolve this:
In your .cpp file, add the following line after the class declaration:
constexpr char foo::baz[];
This declares the definition of the static member baz.
Leave the declaration and initialization of the array within the class definition:
// .hpp struct foo { void bar(); static constexpr char baz[] = "quz"; };
Reason:
The class definition provides the declaration and initializer of the static member. However, the member definition, which allocates memory and initializes the array, needs to be provided separately in the .cpp file. By adding this definition, the linker will be able to find the symbol baz and resolve the undefined reference.
The above is the detailed content of Why Does My Static `constexpr char` Array Cause an 'Undefined Reference'?. For more information, please follow other related articles on the PHP Chinese website!