Home > Backend Development > C++ > Why Do I Get an 'Undefined Reference' Error When Using a Static constexpr char Array in a C Class?

Why Do I Get an 'Undefined Reference' Error When Using a Static constexpr char Array in a C Class?

Susan Sarandon
Release: 2024-12-19 14:13:10
Original
780 people have browsed it

Why Do I Get an

Undefined Reference to Static constexpr char[]

In C , when declaring a static const char array within a class and using it within a member function, one may encounter an error indicating an undefined reference. This error arises due to the separation between declaration and definition in static members.

Problem

Consider the following example:

// header file (foo.hpp)
struct Foo {
  void bar();
  static constexpr char baz[] = "qux";
};

// cpp file (foo.cpp)
void Foo::bar() {
  std::string str(baz); // undefined reference to baz
}
Copy after login

In this example, the static const char array baz is declared within the class but not defined. Compiling the code with GCC will result in the error "undefined reference to baz."

Solution

To resolve this issue, you need to provide a definition for the static member in the cpp file. This definition specifies the array's actual content. In the example above, add the following line to the cpp file:

constexpr char Foo::baz[];
Copy after login

Explanation

In C , static members require both a declaration and a definition, which are separate entities. The declaration specifies the type and name of the member, while the definition provides its actual implementation or value.

For static members declared within a class, the declaration typically appears in the class definition, along with any initializer. However, the definition must be provided outside the class definition, usually in a separate cpp file or at the end of the class definition.

By providing a definition for the static member baz, the linker will be able to resolve its reference and generate the necessary code. Without the definition, the linker cannot determine the actual content of the array and will result in an undefined reference error.

The above is the detailed content of Why Do I Get an 'Undefined Reference' Error When Using a Static constexpr char Array in a C Class?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template